代码之家  ›  专栏  ›  技术社区  ›  no one special

向量传递参数的函数执行器中的C++模糊性

  •  0
  • no one special  · 技术社区  · 8 年前

    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. 余弦 两者都适用 double float ,因此调用不明确。此外,我不能使用 双重的 typename
    2. func 如何根据函数的类型从向量中指定适当数量的参数?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Jarod42    8 年前

    你可以使用 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");
    }