函数指针数组的类模板参数推论适用于clang,但不适用于gcc

时间:2019-01-17 12:37:42

标签: c++ templates c++17

以下代码:

#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>};
                ^

此代码合法吗?如果没有,我该如何解决?

1 个答案:

答案 0 :(得分:4)

我相信该程序格式正确。我本人最近也遇到了类似的问题。当在推断数组参数的过程中需要推导placehoder返回类型时,GCC似乎存在问题。例如,将返回类型明确指定为void将使GCC接受您的代码。

最终,解决方法是拆分声明。

auto *p = f<5>;
std::array{p};