c++ - 类型类方法的参数推导(由 const 限定符重载)在 gcc 中以尾随返回类型失败,但在 clang 中没有

标签 c++ templates language-lawyer c++14 trailing-return-type

没有什么比旧的好 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/

相关文章:

c++ - 使用模板的函数重载

c++ - 编译问题——类型定义、前向声明、 namespace ?

c++ - 为什么这个小改动会停止我的 C++ 程序?

c++ - 如何构建具有特定签名的函数概念?

c++ - 将字符串文字作为类型参数传递给类模板

c++ - 通过未定义的无符号整数读取无符号字符数组是否不安全?

C++ 虚拟继承 - 虚函数 ""的覆盖不明确

php - Twig_SimpleFunction 可以修改上下文吗?

将指向数组的指针转换为指针

c++ - Visual Studio 2015 - 编译器警告(2 级)C4146