Namespaces
Variants

std:: ptr_fun

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
ptr_fun
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
定义于头文件 <functional>
template < class Arg, class Result >

std:: pointer_to_unary_function < Arg,Result >

ptr_fun ( Result ( * f ) ( Arg ) ) ;
(1) (C++11 起弃用)
(C++17 中移除)
template < class Arg1, class Arg2, class Result >

std:: pointer_to_binary_function < Arg1,Arg2,Result >

ptr_fun ( Result ( * f ) ( Arg1, Arg2 ) ) ;
(2) (C++11 起弃用)
(C++17 中移除)

创建一个函数包装器对象(可能是 std:: pointer_to_unary_function std:: pointer_to_binary_function ),从模板参数推导目标类型。

1) 有效地调用 std:: pointer_to_unary_function < Arg,Result > ( f )
2) 有效地调用 std:: pointer_to_binary_function < Arg1,Arg2,Result > ( f )

自 C++11 起,此函数及相关类型已被弃用,取而代之的是更通用的 std::function std::ref ,这两者都能从普通函数创建可调用适配器兼容的函数对象。

目录

参数

f - 指向需要创建包装器的函数的指针

返回值

一个包装 f 的函数对象。

异常

可能抛出实现定义的异常。

示例

#include <algorithm>
#include <functional>
#include <iostream>
#include <string_view>
constexpr bool is_vowel(char c)
{
    return std::string_view{"aeoiuAEIOU"}.find(c) != std::string_view::npos;
}
int main()
{
    std::string_view s = "Hello, world!";
    std::ranges::copy_if(s, std::ostreambuf_iterator<char>(std::cout),
        std::not1(std::ptr_fun(is_vowel)));
#if 0
// C++11 替代方案:
        std::not1(std::cref(is_vowel)));
        std::not1(std::function<bool(char)>(is_vowel)));
        [](char c) { return !is_vowel(c); });
// C++17 替代方案:
        std::not_fn(is_vowel));
#endif
}

输出:

Hll, wrld!

参见

(C++11)
任何可复制构造的可调用对象的可复制包装器
(类模板)
支持给定调用签名中限定符的任何可调用对象的仅移动包装器
(类模板)
(C++17) (C++23)
以给定参数调用任何 Callable 对象 并可指定返回类型 (since C++23)
(函数模板)
(C++17)
创建返回其持有的函数对象结果之补集的函数对象
(函数模板)