【发布时间】:2020-06-18 07:53:24
【问题描述】:
我有一个 std::map 存储一些我想稍后调用的任意方法。
map<string, function<void(void)>> methods;
template<typename R, typename ...P>
void storeMethod(const string& name, const function<R(P...)>& method) {
methods[name] = method;
}
在调用时,我在vector<void*> 中获取调用方法的参数,其中第一个元素是我将存储返回值的指针。
如何自动将这些参数转换为我要调用的方法的相应类型?
我应该以某种方式存储类型吗?
void callMethod(const string& name, vector<void*> parameters) {
auto method = methods[name];
// How to call 'method' with all the parameters casted to the required types?
}
例如,如果我最初用function<int(string a, float b)> 调用storeMethod(),我需要一个通用的方式在callMethod() 中调用它,如下所示:
*((int*)parameters[0]) = method(*((string*)parameters[1]), *((float*)parameters[2]));
【问题讨论】:
-
为什么你得到一个参数为
vector<void*>?当涉及到 C 时,有时需要使用void*,但vector<void*>不是您需要的东西 -
std::function<void(void)>可以存储一个不接受任何参数且不返回任何内容的函数(并用类型擦除对其进行包装)。您不能存储在接受参数或返回的函数中。 -
在 C++ 中,您应该使用模板和参数包而不是这种奇怪的
std::vector<void*>以通用方式转发参数。 -
"void* 因为我正在处理 C 库" ... 好的,但是
vector<void*>不能来自 C 库。你怎么知道实际的类型是什么? -
来自该 C 库的可能类型集是否仅限于某个预定义的子集?