我正在使用这种可变参数模板很长一段时间。有人可以帮帮我吗?我想构建一个能够调用cmath函数并通过向量传递其所有参数的执行程序。请考虑以下代码:
bool execute(const std::string &functionName, const std::vector<double> ¶ms)
{
if (functionName == "cos") return execute(cos, params);
if (functionName == "atan2") return execute(atan2, params);
return false;
}
功能cos
需要一个参数,atan2
需要两个参数。我想要这样的东西:
template <typename... Types>
bool execute(double (*func)(Types...), const std::vector<double> ¶ms)
{
if (params.size() != sizeof...(Types)) {
errorString = "Wrong number of function arguments";
return false;
}
errno = 0;
result = func(params[0]);
errorString = strerror(errno);
return !errno;
}
但是,我遇到了两个问题:
cos
适用于double
和float
,因此调用不明确。此外,我无法使用double
代替typename
强制它。或者还有其他方式?func
时,如何根据函数类型从向量中指定正确数量的参数?或许C ++中已经有一些我不知道的东西? :)非常感谢!
答案 0 :(得分:1)
您可以使用std::index_sequence
,例如:
template <typename... Types, std::size_t ... Is>
double execute(double (*func)(Types...),
const std::vector<double> ¶ms,
std::index_sequence<Is...>)
{
if (params.size() != sizeof...(Types)) {
throw std::runtime_error("Wrong number of function arguments");
}
return func(params[Is]...);
}
template <typename... Types>
double execute(double (*func)(Types...), const std::vector<double> ¶ms)
{
return execute(func, params, std::index_sequence_for<Types...>());
}
并调用它(指定模板参数以修复重载)。
double execute(const std::string &functionName, const std::vector<double> ¶ms)
{
if (functionName == "cos") return (execute<double>)(cos, params);
if (functionName == "atan2") return (execute<double, double>)(atan2, params);
throw std::runtime_error("Unknown function name");
}