std::function、std::bind 、std::placeholder

std::function

       是一种通用、多态的函数封装,它的实例可以对任何可以调用的目标实体进行存储、复制和调用操作,它也是对 C++ 中现有的可调用实体的一种类型安全的包装器(相对来说,函数指针的调用不是类型安全的),换句话说,就是函数的容器。它可以容纳除了类成员函数指针之外的所有可调用对象,它可以用统一的方式处理函数、函数指针、函数对象,并能保存和延迟他们的执行。

std::bind

       用来绑定函数的参数,解决了当需要调用的函数可能存在不能一次性获得所有参数的问题,通过这个函数,我们可以提前将部分参数绑定的函数身上成为一个新对象,然后等到参数齐全时再调用函数

std::placeholder

std::bind绑定参数时作为占位符占用未知参数的位置。如占用参数1位置:std :: placeholders ::_1

 

std::bindstd::placeholder使用:

int foo( int a, int b, int c) {
    return a+b+c;
}
int main () {
    // 第一个参数还没有
    auto bindFoo = std :: bind (foo , std::placeholders ::_1 , 1 ,2);
    bindFoo (1);  // 调用时只需传一个参数
}

std::fuction使用

# include <functional >
# include <iostream >
int foo( int a ) {
    return a ;
}
int main () {
    // std::function定义一个返回int类型,接收一个int参数的函数
    std :: function < int ( int )> func = foo ;
    int b = 10;
    std :: function < int ( int )> func2 = [&]( int a ) -> int {
        return 1+ a + b ;
    };
    std :: cout << func (10) << std :: endl ;
    std :: cout << func2 (10) << std :: endl ;
}

 


版权声明:本文为lisemi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。