//绑定器只能在语句内有效,使用function赋值函数?不知道描述的合理不合理 反正就是 可以拿过来用
//在头文件 funtion
//bind是在boost c++11 新特性
/*
c++ bind绑定器 --> 返回的结果还是一个函数对象
*/
void hello(string str1, string str2){
cout<<str1<<"\n"<<str2<<endl;
}
class TEST{
public:
TEST(){};
~TEST(){};
int sum(int x, int y){
return x * y;
}
};
int main(){
//函数模板不需要给类型 可以自动推演模板类型参数 语法 bind(函数名, 实参...)();
//注意 类模板需要给类型
bind(hello, "hello bind...", "my namne is zhangbuda")();
int ans = bind(&TEST::sum, TEST(), 10, 20)(); //其中TEST() 是函数对象 类的使用需要对象调用
cout<<ans<<endl;
//bind 只能在语句中使用 第二种用法,使用参数占位符
//最多20个参数占位符
cout<<"twice"<<endl;
bind(hello, placeholders::_1, placeholders::_2)("hello bind...", "my namne is zhangbuda");
cout<<bind(&TEST::sum, TEST(), placeholders::_1, placeholders::_2)(30, 40);
//由于绑定除了语句就无法使用,那怎么延伸? 使用function
//通过function 把绑定的功能延伸
function<int (int, int)> func1 = bind(&TEST::sum, TEST(), placeholders::_1, placeholders::_2);
cout<<"\n"<<func1(22, 33);
return 0;
}
c++ | bind 和function
最新推荐文章于 2025-12-05 20:00:00 发布
文章介绍了C++11中的bind绑定器功能,如何在函数模板和类模板中使用,以及如何通过function将绑定功能延伸。重点讲解了bind的使用场景和参数占位符的用法。
2142

被折叠的 条评论
为什么被折叠?



