函数绑定器不能绑定重载函数,无法识别。
仿函数又叫函数绑定器
主要是把一个类的成员函数当成一个普通函数使用。
/*
仿函数又叫函数绑定器
主要是把一个类的成员函数当成一个普通函数使用。
注:绑定时无法进行函数重载。
*/
#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders; //占位
struct MyStruct
{
void show1()
{
cout <<"show1" << endl;
}
void show2(int a)
{
cout << a << endl;
}
void show3(int a,int b)
{
cout << a <<" "<<b << endl;
}
};
void main()
{
MyStruct ms;
ms.show2(10);
//在 vs2015中可以编译,版本不同。vs2015默认是C++14
//cout << typeid(ms.show).name() << endl; // “MyStruct::show”: 函数调用缺少参数列表;请使用“&MyStruct::show
cout << typeid(&MyStruct::show1).name() << endl; //函数原型的地址
//这是C中的函数指针赋值方式,但是在C++中可以这样写,但是却无法 调用
void(MyStruct::*p)(int a) = &MyStruct::show2;
//MyStruct::p(10); //无法调用
//绑定时无法进行函数重载。
auto fun1 = bind(&MyStruct::show1, &ms);
fun1();
//使用默认值
auto fun2 = bind(&MyStruct::show2, &ms, 11);
fun2();
//_1:一个参数
auto fun21 = bind(&MyStruct::show2, &ms,_1);
fun21(22);
//_1,_2:二个参数
auto fun3 = bind(&MyStruct::show3, &ms, _1,_2);
fun3(33, 66);
//设置一个默认值
auto fun31 = bind(&MyStruct::show3, &ms, 33,_1);
fun31(66);
//设置二个默认值
auto fun32 = bind(&MyStruct::show3, &ms, 33,66);
fun32();
cin.get();
}