使用函数指针进行模板推导返回

gil*_*mec 6 c++ templates function-pointers

从g ++ - 5转到g ++ - 6时,我以前工作过的代码失败了; 先前可导出的模板不再可以推导出来.一个最小的例子:

#include <math.h>

template<typename T,typename T1>
T apply(T (*func)(T1), const T1 &val)
{
  return func(val);
}

int main(void)
{
  double val1 = 0.5, val2 = apply(ceil,val1);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

g ++ - 6似乎无法找到正确的版本ceil:

foo.cpp: In function ‘int main()’:
foo.cpp:11:44: error: no matching function for call to ‘apply(<unresolved overloaded function type>, double&)’
   double val1 = 0.5, val2 = apply(ceil,val1);
                                        ^
foo.cpp:4:3: note: candidate: template<class T, class T1> T apply(T (*)(T), const T1&)
 T apply(T (*func)(T), const T1 &val)
   ^~~~~
foo.cpp:4:3: note:   template argument deduction/substitution failed:
foo.cpp:11:44: note:   couldn't deduce template parameter ‘T’
   double val1 = 0.5, val2 = apply(ceil,val1);
Run Code Online (Sandbox Code Playgroud)

g ++ - 5没有问题,并按预期工作.在https://godbolt.org/z/oBSopG上使用Compiler Explorer和g ++ 8 ,我也看到了从clang-3.3(编译)到clang-3.4(不编译)的回复.

鉴于代码仍然不起作用,即使在当前的g ++中,我认为错误是我自己的.我做错了什么,我该如何解决?

πάν*_*ῥεῖ 4

我做错了什么以及如何解决?

解决这个问题的方法是#include <cmath>不使用参考文档#include <math.h>中提到的方法:

#include <cmath> // <<< official header to use.
#include <iostream>

template<typename T,typename T1>
T apply(T (*func)(T1), const T1 &val)
{
  return func(val);
}

int main(void)
{
  double val1 = 0.5, val2 = apply(ceil,val1);

  std::cout << val1 << ' ' << val2<< std::endl;
}
Run Code Online (Sandbox Code Playgroud)