考虑以下程序。有没有一种方法可以实现call()
函数,而不需要在所有的if
声明中?随意更改地图的类型以找到解决方案。 call()
也应该抛出一个异常,如果参数数量不正确。 call()
的接口可以更改,但函数的名称,参数数组的指针和参数的数量仅在运行时才可知。从具有可变数字参数的函数的指针图调用函数
#include <iostream>
#include <string>
#include <map>
#include <cmath>
#include <boost/any.hpp>
using namespace std;
typedef double(*PF1)(double);
typedef double(*PF2)(double, double);
typedef double(*PF3)(double, double, double);
map<string, boost::any> m = {
{"sin", static_cast<PF1> (std::sin)},
{"pow", static_cast<PF2> (std::pow)}
// other
};
double call(string name, double* args, int nargs) {
if (name == "sin" && nargs == 1)
return boost::any_cast<PF1>(m[name])(args[0]);
else if (name == "pow" && nargs == 2)
return boost::any_cast<PF2>(m[name])(args[0], args[1]);
// etc...
}
int main() {
double n[] = {1, 2, 3, 4, 5, 6};
int narg1 = 1, narg2 = 2; // known at runtime
double r = call("sin", n, narg1);
r = call("pow", n, narg2);
}
可变模板可能会有所帮助。 –
是的,我问他们如何帮助... – Martin
给他们一个尝试,找出?! –