c++ - 函数指针数组的类模板参数推导适用于clang,但不适用于gcc
问题描述
以下代码:
#include <array>
template <int i>
auto f(){}
int main () {
std::array{f<5>};
}
使用 clang 7.0 编译,但使用 gcc 8.2 失败并显示消息
prog.cc: In function 'int main()':
prog.cc:7:20: error: class template argument deduction failed:
std::array{f<5>};
^
prog.cc:7:20: error: no matching function for call to 'array(<unresolved overloaded function type>)'
In file included from prog.cc:1:
/opt/wandbox/gcc-8.2.0/include/c++/8.2.0/array:244:5: note: candidate: 'template<class _Tp, class ... _Up> std::array(_Tp, _Up ...)-> std::array<typename std::enable_if<(is_same_v<_Tp, _Up> && ...), _Tp>::type, (1 + sizeof... (_Up))>'
array(_Tp, _Up...)
^~~~~
/opt/wandbox/gcc-8.2.0/include/c++/8.2.0/array:244:5: note: template argument deduction/substitution failed:
prog.cc:7:20: note: couldn't deduce template parameter '_Tp'
std::array{f<5>};
^
In file included from prog.cc:1:
/opt/wandbox/gcc-8.2.0/include/c++/8.2.0/array:94:12: note: candidate: 'template<class _Tp, long unsigned int _Nm> array(std::array<_Tp, _Nm>)-> std::array<_Tp, _Nm>'
struct array
^~~~~
/opt/wandbox/gcc-8.2.0/include/c++/8.2.0/array:94:12: note: template argument deduction/substitution failed:
prog.cc:7:20: note: couldn't deduce template parameter '_Tp'
std::array{f<5>};
^
这段代码合法吗?如果没有,我该如何解决?
解决方案
我相信这个程序已经很好地形成了。我最近自己也遇到了类似的问题。GCC 在推导数组参数的过程中需要推导占位符返回类型时似乎存在问题。例如,明确指定返回类型void
会使 GCC 接受您的代码。
最终,解决方法是拆分声明。
auto *p = f<5>;
std::array{p};
推荐阅读
- php - PHP $_POST 变量变量不起作用
- javascript - 我可以在 Dialogflow 的内联编辑器中使用意图参数吗?
- django - Django:多个管理页面使用相同的模型但不同的身份验证模式
- android - 扩展 RoomDatabase 的 Singleton Kotlin 类只被调用一次
- algorithm - C - 嵌套循环的时间复杂度
- scala - 如何对应用于输入的验证规则进行单元测试
- kotlin - 如何转换反应堆通量
到输入流 - javascript - dygraph:x轴y轴设置最小值和最大值
- javascript - chrome 扩展:OAuth2 请求失败:服务响应错误:“错误请求”
- reactjs - React 上的输入字段状态更改