Namespaces
Variants

std::ptr_fun

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装对象
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器和适配器
(*至 C++17*)
(*至 C++17*)
(*至 C++17*)
(*至 C++17*)
(*至 C++17*)(*至 C++17*)(*至 C++17*)(*至 C++17*)
(*至 C++20*)
(*至 C++20*)
(*至 C++17*)(*至 C++17*)
(*至 C++17*)(*至 C++17*)

(*至 C++17*)
(*至 C++17*)(*至 C++17*)(*至 C++17*)(*至 C++17*)
(*至 C++20*)
(*至 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)
创建返回其持有的函数对象结果之补集的函数对象
(函数模板)