gpt4 book ai didi

c++ - 映射中具有重载 () 运算符的仿函数 - 仅按需评估

转载 作者:太空狗 更新时间:2023-10-29 21:21:12 25 4
gpt4 key购买 nike

我想要一个具有重载的 () 运算符 的仿函数对象,并将这些重载版本中的每一个存储在映射中。这样我就可以将我的逻辑放在一个类中,这里是我试图完成的一小段代码:

#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;
}

最佳答案

您想将某些参数“绑定(bind)”到一个函数吗?当然!

#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::functionstd::bind 可以在 functionoids(就像你的)、lambdas、函数指针、成员函数上工作......它们是惊人的。 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);

关于c++ - 映射中具有重载 () 运算符的仿函数 - 仅按需评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com