调用在C ++中作为参数传递的同一模板函数的两个版本

时间:2019-01-14 20:22:28

标签: c++ templates boost c++14 template-deduction

我想在一个函数中调用同一函数的两个版本。例如:

template<class F>
auto ulp_error(F f, float x)
{
    float f1 = f(x);
    double x2 = x;
    float f2 = static_cast<float>(f(x2));
    return boost::math::float_distance(f1, f2);
}

现在我想通过以下方式调用此函数:

ulp_error(std::log, 1.2f);

但是在clang-1000.11.45.5上出现以下错误:

fatal error: no matching function for call to 'ulp_error'
    ulp_error(std::log, 1.2f);
note: candidate template ignored: couldn't infer template argument 'F'

好的,这怎么样?

ulp_error<decltype(std::log)>(std::log, 1.2f);

出现以下错误:

fatal error: reference to overloaded function could not be resolved; did you mean to call it?
    ulp_error<decltype(std::log)>(std::log, 1.2f);

如何将std::log作为参数传递给函数,并用两种不同的类型进行调用?

1 个答案:

答案 0 :(得分:3)

也许如下?

ulp_error([](auto x){ return std::log(x); }, 1.2f);

我的意思是……std::log是一个重载函数;因此,仅使用std::log(或decltype(std::log))不起作用,因为编译器无法选择正确的版本。并且您不能同时传递它们。

但是将其传递到通用模板中后,可以通过x lambda参数的类型来选择更正的版本。

例如,另一种可能的解决方案应强制转换为正确的类型

ulp_error(static_cast<double(*)(double)>(&std::log), 1.2f);

但是(MHO)我发现这种语法有点难看。