Namespaces
Variants

std::unary_function

来自 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++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< typename ArgumentType, typename ResultType >
struct unary_function;
(C++11 弃用)
(C++17 移除)

std::unary_function 是用于创建带一个参数的函数对象的基类。

std::unary_function未定义 operator();派生类预计会定义这个成员。std::unary_function仅提供两种类型——argument_type 和 result_type——由模板参数定义。

一些标准库函数对象适配器,例如 std::not1,要求它们所适配的函数对象具有某些已定义的类型;std::not1 要求被适配的函数对象具有一个名为 argument_type 的类型。从 std::unary_function 派生出接受一个参数的函数对象是使它们与这些适配器兼容的一种简便方法。

std::unary_function在 C++11 中被弃用。

成员类型

类型 定义
argument_type ArgumentType
result_type ResultType

示例

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
struct less_than_7 : std::unary_function<int, bool>
{
    bool operator()(int i) const { return i < 7; }
};
int main()
{
    std::vector<int> v(10, 7);
    v[0] = v[1] = v[2] = 6;
    std::cout << std::count_if(v.begin(), v.end(), std::not1(less_than_7()));
    // C++11 解决方案:
    // 转换为 std::function<bool (int)> 的方式 - 即使使用 lambda 表达式
    // std::cout << std::count_if(v.begin(), v.end(),
    //     std::not1(std::function<bool (int)>([](int i) { return i < 7; })));
}

输出:

7

参见

(C++11)
任意可复制构造可调用对象的可复制包装器
(类模板)
支持给定调用签名中限定符的任意可调用对象的仅移动包装器
(类模板)
(deprecated in C++11) (removed in C++17)
从函数指针创建适配器兼容的函数对象包装器
(函数模板)
(deprecated in C++11) (removed in C++17)
一元函数指针的适配器兼容包装器
(类模板)
(deprecated in C++11) (removed in C++17)
适配器兼容的二元函数基类
(类模板)