std::bind

#include <iostream>
#include <functional>

void fun(int val, int val2, int val3);
class Func{
public:
    void fun(int val, int val2);
    static void staticFun(int val, int val2);
};
int main()
{
    int p1 = 1, p2 = 2, p3 = 3; 
    
    // p3 passed by value
    std::function<void (int,int)> fun_bind = 
        std::bind(fun, std::placeholders::_1, std::placeholders::_2, p3); 
    
    fun_bind(p1, p2); // p1 and p2 passed by reference !! 
    
    Func func;
    
    // VERY IMPORTANT
    // bind will call copy constructor to produce a object same with func
    // use a pointer or smart_pointer(share_ptr) is a better choice
    
    auto fun_bind2 = std::bind(&Func::fun, func, std::placeholders::_1, 2); // Don't forget &
    
    
    fun_bind2(1);
    auto fun_bind3 = std::bind(&Func::staticFun, std::placeholders::_1, 2); 
    fun_bind3(1);
    return 0;
}
void fun(int val, int val2, int val3) {
    std::cout << val << " " << val2 <<" " << val3 << std::endl;
}
void Func::fun(int val, int val2) {
     std::cout << "Func " <<val << " " << val2 << std::endl;
}
void Func::staticFun(int val, int val2) {
      std::cout << "Func_static " <<val << " " << val2 << std::endl;
}

std::function

引用

std::function< int(int)> Functional;
// 普通函数
int TestFunc(int a) { return a; }

// Lambda表达式
auto lambda = [](int a)->int{ return a; };

// 仿函数(functor)
class Functor
{
public:
    int operator()(int a) { return a; }
};

// 1.类成员函数, 2.类静态函数
class TestClass
{
public:
    int ClassMember(int a) { return a; }
    static int StaticMember(int a) { return a; }
};
int main() {
    // 普通函数
    Functional = TestFunc;
    int result = Functional(10);
    cout << "普通函数:"<< result << endl;

    // Lambda表达式
    Functional = lambda;
    result = Functional(20);
    cout << "Lambda表达式:"<< result << endl;

    // 仿函数
    Functor testFunctor;
    Functional = testFunctor;
    result = Functional(30);
    cout << "仿函数:"<< result << endl;

    // 类成员函数
    TestClass testObj;
    Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
    result = Functional(40);
    cout << "类成员函数:"<< result << endl;
    
    // 类静态函数
    Functional = TestClass::StaticMember;
    result = Functional(50);
    cout << "类静态函数:"<< result << endl;
    return 0;
}

shiyang6017
164 声望60 粉丝

引用和评论

0 条评论