函数执行器中的C ++歧义,带有在向量中传递的参数

时间:2017-08-24 13:18:28

标签: c++ c++11 variadic-templates

我正在使用这种可变参数模板很长一段时间。有人可以帮帮我吗?我想构建一个能够调用cmath函数并通过向量传递其所有参数的执行程序。请考虑以下代码:

bool execute(const std::string &functionName, const std::vector<double> &params)
{
    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> &params)
{
    if (params.size() != sizeof...(Types)) {
        errorString = "Wrong number of function arguments";
        return false;
    }

    errno = 0;
    result = func(params[0]);
    errorString = strerror(errno);
    return !errno;
}

但是,我遇到了两个问题:

  1. 函数cos适用于doublefloat,因此调用不明确。此外,我无法使用double代替typename强制它。或者还有其他方式?
  2. 当我尝试调用函数func时,如何根据函数类型从向量中指定正确数量的参数?
  3. 或许C ++中已经有一些我不知道的东西? :)非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以使用std::index_sequence,例如:

template <typename... Types, std::size_t ... Is>
double execute(double (*func)(Types...),
               const std::vector<double> &params,
               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> &params)
{
    return execute(func, params, std::index_sequence_for<Types...>());
}

并调用它(指定模板参数以修复重载)。

double execute(const std::string &functionName, const std::vector<double> &params)
{
    if (functionName == "cos") return (execute<double>)(cos, params);
    if (functionName == "atan2") return (execute<double, double>)(atan2, params);
    throw std::runtime_error("Unknown function name");
}