没有什么比旧的好 MCVE 更清楚的了:
struct X {
auto get(int) const -> int { return {}; }
auto get(int) -> int { return {}; }
};
template <class R> auto f(auto (X::*)(int) const -> R) {}
// ^~~~ ~~~~
// trailing return type
int main() {
f(&X::get);
}
这在 g++ (4.9.2 & 5.1.0) 中失败。但是,如果使用旧的返回类型:
template <class R> auto f(R (X::*)(int) const) {}
// ^
// old return type
有用。
在 clang (3.5.0) 上,两种变体都有效。
我知道在推断返回类型及其范围时尾随返回类型会发生变化,因此我不会很快将其转换为 gcc 错误。那么标准是怎么说的呢?哪个编译器是对的?
我认为错误中最重要的信息是
couldn't deduce template parameter ‘R’`
g++ 完整消息:
main2.cpp: In function ‘int main()’:
main2.cpp:21:12: error: no matching function for call to ‘f(<unresolved overloaded function type>)’
f(&X::get);
^
main2.cpp:18:25: note: candidate: template<class R, class auto:1> auto f(auto:1 (X::*)(int) const)
template <class R> auto f(auto (X::*)(int) const -> R) {}
^
main2.cpp:18:25: note: template argument deduction/substitution failed:
main2.cpp:21:12: note: types ‘auto:1 (X::)(int) const’ and ‘int (X::)(int)’ have incompatible cv-qualifiers
f(&X::get);
^
main2.cpp:21:12: note: couldn't deduce template parameter ‘R’
<builtin>: recipe for target 'main2' failed
make: *** [main2] Error 1
最佳答案
正如问题中所指出的,这是一个 gcc 错误,已在版本 6 中修复
gcc.gnu.org/bugzilla/show_bug.cgi?id=69139
关于c++ - 类型类方法的参数推导(由 const 限定符重载)在 gcc 中以尾随返回类型失败,但在 clang 中没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229359/