首页 > 解决方案 > 带函数指针的模板推导还原

问题描述

我以前工作的代码在从 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;
}

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);

g++-5 没有问题并且按预期工作。在https://godbolt.org/z/oBSopG使用带有 g++ 8 的编译器资源管理器,我还看到从 clang-3.3(编译)到 clang-3.4(不编译)的恢复。

鉴于代码仍然无法工作,即使在当前的 g++ 中,我认为错误是我的一部分。我做错了什么,我该如何解决?

标签: c++templatesfunction-pointers

解决方案


我做错了什么,我该如何解决?

解决这个问题的方法是#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;
}

推荐阅读