代码示例:
#include<boost/function.hpp>
#include<boost/bind.hpp>
#include<iostream>
typedef boost::function<int(int)> Func;
int test(int num,char ch)
{
std::cout<<num<<" "<<ch<<std::endl;
}
int test01(int close_file)
{
std::cout<<"close file"<<std::endl;
}
int main()
{
//operation 返回值是int,但是参数为空,bind了一个有参数的函数
//这种方式只能在bind时指定参数,后续不能通过operation再传入参数了
boost::function<int()> operation(boost::bind(test,1,'C'));
operation();
//这里的定义和函数的类型相同,如果bind时指定了参数,后续指定参数调用就没有作用了,这里可以理解为接口是动态绑定的,但是参数不是动态绑定的,和多态好像一样
//比如这里传入了2 'D',下面调用时传入了3 'E',其实打印出来的还是2 ‘D’
boost::function<int(int,char)> operation1(boost::bind(test,2,'D'));
operation1(3,'E');
//所以如果需要动态传入参数,需要通过_1,_2来动态指定第一个和第二个参数
boost::function<int(int,char)> operation2(boost::bind(test,_1,_2));
operation2(3,'E');
Func f(boost::bind(test01,1));
f(1);
}
执行./a.out结果:
1 C
2 D
3 E
close file
编译命令:
这里通过-I参数指定boost库头文件的位置。
g++ test.cpp -I/home/uxdb/uxdb-ng/boost_1_62_0