C++ functional

141 阅读2分钟

C++ functional

docs.microsoft.com/zh-cn/cpp/s…

定义有助于构造 函数对象的 C++ 标准库函数,也称为 functor 及其绑定器。 函数对象是用于定义 operator() 的类型的对象。 函数对象可以是函数指针,但该对象更常用于存储可在函数调用过程中访问的其他信息。

function 类

可调用对象的包装器。

语法

template <class Fty>
class function  // Fty of type Ret(T1, T2, ..., TN)
    : public unary_function<T1, Ret>       // when Fty is Ret(T1)
    : public binary_function<T1, T2, Ret>  // when Fty is Ret(T1, T2)
{
public:
    typedef Ret result_type;
    
    //构造函数
    function();
    function(nullptr_t);
    function(const function& right);
    template <class Fty2>
        function(Fty2 fn);
    template <class Fty2, class Alloc>
        function(reference_wrapper<Fty2>, const Alloc& Ax);
    //分配
    template <class Fty2, class Alloc>
        void assign(Fty2, const Alloc& Ax);
    template <class Fty2, class Alloc>
        void assign(reference_wrapper<Fty2>, const Alloc& Ax);
    //赋值运算符
    function& operator=(nullptr_t);
    function& operator=(const function&);
    template <class Fty2>
        function& operator=(Fty2);
    template <class Fty2>
        function& operator=(reference_wrapper<Fty2>);
    //交换
    void swap(function&);
    //是否为空
    explicit operator bool() const;
    //调用
    result_type operator()(T1, T2, ....., TN) const;
    //类型查询
    const std::type_info& target_type() const;
    //目标//测试存储的可调用对象是否可按指定方式调用
    template <class Fty2>
        Fty2 *target();
    template <class Fty2>
        const Fty2 *target() const;
    //删除的运算符
    template <class Fty2>
        void operator==(const Fty2&) const = delete;
    template <class Fty2>
        void operator!=(const Fty2&) const = delete;
};

assign

将可调用对象分配给此函数对象。

template <class Fx, class Alloc>
    void assign(
        Fx _Func,
        const Alloc& Ax);
​
template <class Fx, class Alloc>
    void assign(
        reference_wrapper<Fx> _Fnref,
        const Alloc& Ax);

参数

_Func 可调用的对象。

_Fnref 包含可调用对象的引用包装器。

Ax 分配器对象。

注解

每个成员函数使用作为 operand 传递的可调用对象替换由 *this 保留的callable object。 两者都使用分配器对象 Ax 分配存储。

运算符未指定

测试存储的可调用对象是否存在。

C++复制

operator unspecified();

注解

运算符返回一个值,该值仅当对象不为空时,才可转换为 bool true 值。 可将它用于测试对象是否为空。

bind

将自变量绑定到可调用对象。调用包装

C++复制

template <class FT, class T1, class T2, ..., class TN>
    unspecified bind(FT fn, T1 t1, T2 t2, ..., TN tN);
​
template <class RTy, class FT, class T1, class T2, ..., class TN>
    unspecified bind(FT fn, T1 t1, T2 t2, ..., TN tN);

参数

FT 要调用的对象的类型。 例如,函数、函数对象、函数指针/引用或成员函数指针的类型。

RTy 返回类型。 指定后,它将是绑定调用的返回类型。 否则,返回类型是返回类型的 FT返回类型。

TN 第 N 个调用参数的类型。

fn 要调用的对象。

tN 第 N 个调用参数。

www.jianshu.com/p/82407fb43…

#include <functional> //bind函数 placeholders命名空间int Plus(int x, int y) {
    return x + y;
}
​
int PlusOne(int x) {
    auto func = std::bind(Plus, std::placeholders::_1, 1);
    return func(x);
}
​
int main()
{
    std::cout << PlusOne(9) << std::endl; //结果 10
    return 0;
}
​

\