gpt4 book ai didi

c++ - 在运行时获取命名空间中的函数列表?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:15 25 4
gpt4 key购买 nike

是否可以在运行时获取某个命名空间中的函数列表或程序中的所有函数?

我有一个函数指针映射,我需要自己向它添加命令,但我想:为什么不创建一个命名空间并让程序在运行时完成工作呢?

类似于(伪代码):

typedef bool (*command)(void);
namespace Commands
{
bool Start(void)
{
return true;
}
bool End(void)
{
return true;
}
};
std::map<std::string,command> CommandMap;
main()
{
for(each function in namespace Commands)
{
CommandMap[std::string(function_name)] = function;
}
CommandMap["Start"]();
CommandMap["End"]();
return 0;
}

代替

std::map<std::string,command> CommandMap;
main()
{
CommandMap["Start"] = Commands::Start;
CommandMap["End"] = Commands::End;
//list of thousands of other commands......
CommandMap["Start"]();
CommandMap["End"]();
return 0;
}

这可以用 C++ 或 C++11 实现吗?或者我的目标有任何替代方案吗?

最佳答案

否(必须为 30 个字符)。

编辑:这与我关于您拥有多少控制权的评论一致。您可以将所有函数重新定义为仿函数,并让构造函数将自己注册到某个数组中。您的基类将如下所示:

EDIT2:阅读关于所有具有相同参数和返回类型的函数的评论,使其更清晰一些。

class myFunctorBaseClass
{
public:
myFunctorClass () : {//register myself, no duplicates}
virtual int operator () (int);//Whatever types you want
};

class myFunctor: public myFunctorBaseClass //Define as many of these as you need
{
public:

int operator() (int y) { return y; } // Define this as whatever you want
}

这显然取决于正在构建的对象,但假设它们都是作为初始化步骤,这会得到你想要的。

注意:这可能不完整/未编译。我只是想把它写下来,但它应该很接近。如果您对其工作原理有疑问,您需要的引用是“仿函数”。

关于c++ - 在运行时获取命名空间中的函数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485006/

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