gpt4 book ai didi

c++ - 调用映射键来调用需要参数的函数——如何开始工作

转载 作者:搜寻专家 更新时间:2023-10-31 01:09:52 24 4
gpt4 key购买 nike

这是我的代码。

#include <map>
#include <string>
#include <algorithm>

class maptest {
public:
int doubler(int val) { return val * 2; }
int halver(int val) { return val / 2; }
int negativer(int val) { return val > 0 ? -val : val; }
};


int main() {

const char* const ID[] = {"doubler", "halver", "negativer" };
int ID_SIZE = sizeof(ID) / sizeof(*ID);

//signature of maths functions
typedef int (maptest::*mathfunc)(int);


mathfunc mfuncs[] = { &maptest::doubler, &maptest::halver, &maptest::negativer};

std::map<std::string, mathfunc> mathmap;

for(int i = 0; i < ID_SIZE; ++i) {
mathmap.insert(std::make_pair(ID[i], mfuncs[i]));
}

//C2064: term does not evaluate to a function taking 1 argument
int result = *mathmap["doubler"](3);

return 0;
}

我认为如果没有要传递给函数的参数,这会起作用。但是如何以这种方式传递参数呢?

最佳答案

您的 mathfunc 是成员函数,因此您需要一个对象来调用它们:

maptest mt;
int result = (mt.*(mathmap["doubler"]))(3);

或者,您可以将成员函数设为静态:

class maptest {
public:
static int doubler(int val) { return val * 2; }
static int halver(int val) { return val / 2; }
static int negativer(int val) { return val > 0 ? -val : val; }
};

然后相应地定义mathfunc:

typedef int (*mathfunc)(int);

这将允许您以在原始帖子中调用它们的方式调用它们:

typedef int (*mathfunc)(int);

请注意,使此设计更灵活的一种方法是使用 std::function,这将允许您 pass any type of callable object .例如:

typedef std::function<int(int)> mathfunc;

mathfunc mfuncs[] = {
&maptest::doubler,
&maptest::halver,
&maptest::negativer,
[] (int i) { return i * 2; } // <== A LAMBDA...
};

关于c++ - 调用映射键来调用需要参数的函数——如何开始工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16562698/

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