异构函数指针的c ++ std :: map [英] c++ std::map of heterogeneous function pointers
问题描述
可以存储指向各种异构函数的指针,如:
在标题中:
int functionA(int param1);
void functionB(void);
基本上这部分我不知道如何写:
typedef ?? boost :: function< void(void)> ?? functionPointer;
之后:
map< char *,functionPointer> _myMap;
在.cpp中
void CreateFunctionMap()
{
_myMap [functionA] =& functionA;
_myMap [functionB] =& functionB;
...
}
然后重复使用如下:
void execute(int argc,char * argv [])
{
if(argc> 1){
int param = atoi(argv [1]);
int答案;
functionPointer mfp;
mfp = map [argv [0]];
answer = * mfp(param);
}
else {
* map [argv [0]];
}
}
等。
谢谢
- 编辑 -
给出更多的信息:
这个问题的原因是我正在为已经存在的应用程序实现一个下拉的地震风格控制台。这样,我可以提供运行时命令行用户输入,以访问各种类型的各种已编码的功能,例如:
/ exec< functionName> ; <参数1> < param2的> ...
每个函数都有不同的类型,所以你需要某种类型的擦除。你可以使用最通用的:Boost.Any。您可以拥有的
函数调用并具有映射中的所有函数为空函数: boost :: any
,但您需要知道函数的类型才能另外,如果你提前知道你的想法,你可以将它们绑定到$ {code> bind function< void()>
。即使你不这样做,你也可以通过将参数绑定到引用来消除它,然后在调用时用适当的参数填充引用的变量。
Is it possible to store pointers to various heterogenous functions like:
In the header:
int functionA (int param1);
void functionB (void);
Basically this would the part I don't know how to write:
typedef ??boost::function<void(void)>?? functionPointer;
And afterwards:
map<char*,functionPointer> _myMap;
In the .cpp
void CreateFunctionMap()
{
_myMap["functionA"] = &functionA;
_myMap["functionB"] = &functionB;
...
}
And then reuse it like:
void execute(int argc, char* argv[])
{
if(argc>1){
int param = atoi(argv[1]);
int answer;
functionPointer mfp;
mfp = map[argv[0]];
answer = *mfp(param);
}
else{
*map[argv[0]];
}
}
etc.
Thanks
--EDIT--
Just to give more info:
The reason for this question is that I am implementing a drop-down "quake-style" console for an already existing application. This way I can provide runtime command line user input to access various already coded functions of various types i.e.:
/exec <functionName> <param1> <param2> ...
Each of your functions has a different type, so you need some kind of type erasure. You could use the most generic of them: Boost.Any. You can have a map
of boost::any
, but you need to know the type of the function in order to get it back and call it.
Alternatively, if you know your arguments ahead of time you can bind
them with the function call and have all functions in the map be nullary functions: function< void() >
. Even if you don't, you may be able to get away with it by binding the argument to references, and then at call time fill the referred variables with the appropiate arguments.
这篇关于异构函数指针的c ++ std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!