c++ - 带函数指针的模板推导还原
问题描述
我以前工作的代码在从 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++ 中,我认为错误是我的一部分。我做错了什么,我该如何解决?
解决方案
我做错了什么,我该如何解决?
解决这个问题的方法是#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;
}
推荐阅读
- python - Flair Framework with PyTorch - OverflowError: int too big to convert
- html - 在 CSS 中创建一个聊天气泡,边框围绕 ::before 属性
- php - 卷曲的回声响应
- typescript - 使用 TypeScript 在 Vue 3 中创建全局过滤器
- python - 如何填充元组列表,使用 for 循环在 Python 中保留其结构?
- php - 如何迭代嵌套的 stdClass 对象?
- r - 将 tibble 与来自同一 tibble 的数据合并
- keras - 预期 ndim=3,发现 ndim=4。在 keras 后端使用 K.function() 获取模型中的中间层时
- django - 使用 Google 分析的 Django Allauth 注册活动
- javascript - 如何设置输入条件以在 Vuejs 中关闭事件?