【问题标题】:Question about trailing return type in C++17关于 C++17 中的尾随返回类型的问题
【发布时间】:2019-07-27 17:15:59
【问题描述】:

我有以下编译好的代码:

template <typename T> 
struct A {T t;};

template <typename T> // 1 
A(T) -> A<T>;  // function template declaration with trailing return type compiles fine.

但同一函数声明的以下变体无法编译:

template <typename T>  // 2
auto A(T) -> A<T>; // error: redefinition of 'A' as different kind of symbol

template <typename T>  // 3
A<T> A(T); // error: redefinition of 'A' as different kind of symbol

请帮助我理解为什么那些没有编译的原因

【问题讨论】:

  • 问这样的问题时,一定要提供编译错误的文本。
  • @NeilButterworth 添加了实际的编译错误消息。谢谢

标签: c++ templates c++17 template-argument-deduction function-templates


【解决方案1】:

// 带有尾随返回类型的函数模板声明编译良好。

template <typename T> // 1 
A(T) -> A<T>;  // function template declaration with trailing return type compiles fine.

不完全是。

对于具有显式尾随返回类型的函数声明,您必须在函数名称前添加auto

您的“1”代码示例是新的 C++17 用户定义推导指南(有关详细信息,请参阅 this page)。

给定您的模板 A 类,您是在说编译器在定义变量时如下所示

A  a{42l};

您正在定义一个A&lt;long&gt; 变量,因为模板形参的类型是从构造函数的参数(42l) 推导出来的。

关于以下代码

template <typename T>  // 2
auto A(T) -> A(T); // error: use of class template 'A' requires template  arguments

现在您在名称前正确使用了auto,因此您声明了一个函数;不幸的是,名称不能是A(它是结构的名称),返回类型不能是A(T)(可能是A&lt;T&gt;

template <typename T>  // 3
A<T> A(T); // error: redefinition of 'A' as different kind of symbol

现在您正确地声明了返回 A&lt;T&gt; 的模板函数,但仍然存在另一个问题:名称不能是 A(它是结构的名称)

【讨论】:

  • 是的,这是 //2 中返回类型的拼写错误。我现在将其更正为 A。谢谢。
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2015-09-10
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多