我希望有一个带有重载() operator
的仿函数对象,并将这些重载版本中的一个存储在地图中。通过这种方式,我可以将我的逻辑保留在一个类中,这是我想要完成的一个小代码:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class functor{
public:
void operator()(int i){
cout << i << endl;
}
void operator()(string s){
cout << s << endl;
}
void operator()(int i, int j){
cout << i+j << endl;
}
};
int main(){
// i know i should put something here thats not "functor"
// but i have no idea what.
map<int,functor> hTable;
// is there a way to add elements into a table somehow like this...
hTable[0] = functor()(2);
hTable[1] = functor()("foo and bar are overrated, boo.");
hTable[2] = functor()(2,3);
// and fire the function in the table simply like this?
hTable[0];
cin.get();
return 0;
}
答案 0 :(得分:3)
你想&#34;绑定&#34;函数的某些参数?当然!
#include <functional>
int main(){
// A map of integers to functions
//each function takes no parameters () and returns nothing (void)
map<int,std::function<void()>> hTable;
// add elements into a table like this...
hTable[0] = std::bind(functor(), 2);
hTable[1] = std::bind(functor(), "foo and bar are overrated, boo.");
hTable[2] = std::bind(functor(), 2, 3);
// and fire the function in the table simply like this
hTable[0]();
cin.get();
return 0;
}
在此处观看:http://coliru.stacked-crooked.com/a/8042e98b19ccbf6b
此外,std::function
和std::bind
可以处理功能块(如你的),lambda,函数指针,成员函数......它们非常棒。 std::bind
也有占位符,也很棒:
double divide(int left, int right) {return (double)left/right;}
//brings _1 into the current scope
using std::placeholders;
//bind the first input as the first parameter, bind 100 to the second parameter
std::function<double(int)> percent = std::bind(divide, _1, 100);
//the resulting function only has one input:
double half = percent(50);