std::function

 

头文件:<functional>

定义:

template< class R, class... Args >
class function<R(Args...)>;

 

std::functional 是一个类模板,它是一个通用的多态函数包装器。std::funcion 的实例可以存储、拷贝、和引用任何拷贝构造的目标,函数,lambda表达式、绑定的表达式、或者其他函数对象,比如成员函数指针或者成员变量指针。

被保存的调用对象叫 std::function 调用对象。如果一个 std::function 没有包含目标,那么它被成为空。一个空的引用目标会抛出一个 std::bad_function_call  的异常。

 

使用实例:

#include<iostream>
#include<functional>

struct Foo
{
    Foo(int num) : num_(num){}
    void print_add(int i) const{
        // std::cout << "Foo print_add : " << "num_ + i : " << num_ + i << std::endl;
        std::cout << "num_ : " << num_ << ", i : " <<  i << " ,num_ + i : " << num_ + i << std::endl;
    }
    int num_;
};

void print_num(int i) {
    std::cout << "print_num : " << i << "\n";
}

struct PrintNum{
    void operator()(int i) const
    {
        std::cout << "PrintNum operator " << i << "\n";
    }
};

int main()
{
    // store a free function
    std::function<void(int)> f_display = print_num;
    f_display(-9);

    // store a lambda
    std::function<void()> f_display_2 = []() { print_num (1); };
    f_display_2();

    // store the result of a call to std::bind
    std::function<void()> f_display_3 = std::bind(print_num, 2);
    f_display_3();

    // store a call to a member function
    std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
    const Foo foo(3);
    f_add_display(foo, 4);
    f_add_display(5,6);
    foo.print_add(2);

    // store a call to a data member accessor
    std::function<int(Foo const&)> f_num = &Foo::num_;
    std:: cout << "num_ : " << f_num(foo) << "\n";

    // strore a call to a member function and object
    using std::placeholders::_1;
    std::function<void(int)> f_add_display_2 = std::bind(&Foo::print_add, foo, _1);
    f_add_display_2(7);


    // store a call to a function object
    std::function<void(int)> f_add_display_3 = std::bind(&Foo::print_add, &foo, _1);
    f_add_display_3(8);

    // store a call to a function object
    std::function<void(int)> f_display_obj = PrintNum();
    f_display_obj(9);

    auto facotrial = [](int n) {
        // store a lambda object to emulate "recursive lambda"; adare of extra overhead
        std::function<int(int)> fac = [&](int n) { return (n < 2) ? 1 : n*fac(n-1); };
        return fac(n);
    };

    for (int i{5}; i != 8; ++i) {
        std::cout << i << " ! = " << facotrial(i) << "; " ;
    }

    return 0;
}

 

posted @ 2022-06-08 15:39  王清河  阅读(1465)  评论(0编辑  收藏  举报