![](/img/trans.png)
[英]Lambda expression in C++17: trailing return type vs static_cast for type conversion
[英]Question about trailing return type in C++17
我有以下编译好的代码:
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
请帮助我理解为什么那些没有编译的理由
//具有尾随返回类型的函数模板声明编译正常。
template <typename T> // 1
A(T) -> A<T>; // function template declaration with trailing return type compiles fine.
不完全是。
对于具有显式尾随返回类型的函数声明,您必须在函数名称之前添加auto
。
您的“1”代码示例是新的C ++ 17用户定义演绎指南(有关详细信息,请参阅此页面 )。
给定您的模板A
类,您说的是编译器,当您按如下方式定义变量时
A a{42l};
您正在定义A<long>
变量,因为模板参数的类型是从构造函数的参数( 42l
)推导出来的。
关于以下代码
template <typename T> // 2
auto A(T) -> A(T); // error: use of class template 'A' requires template arguments
现在你在名字之前使用正确的auto
,所以你要声明一个函数; 遗憾的是,名称不能是A
(它是结构的名称),返回类型不能是A(T)
(可能是A<T>
)
template <typename T> // 3
A<T> A(T); // error: redefinition of 'A' as different kind of symbol
现在你正确地声明一个返回A<T>
的模板函数但仍然是另一个问题:名称不能是A
(它是结构的名称)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.