Home >Backend Development >C++ >Can C 20 Class Template Constructors Omit Redundant Template Parameter Lists?
Can Class Template Constructors Have a Redundant Template Parameter List in C 20?
In C 17, it was permissible to declare class template constructors with a redundant template parameter list, as exemplified by the following code:
template<typename T> struct S { S<T>(); };
However, with the advent of C 20 and the implementation of compatibility changes, the aforementioned code now raises an error on GCC trunk (for -std=c 20). Clang trunk, on the other hand, compiles the code without issue. This inconsistency begs the question: is this a bug or an intended breaking change that has yet to be implemented fully across compilers?
The Answer
The answer lies in a subtle change in the C 20 specification. Specifically, the following section has been revised:
[class.ctor]
"A constructor is introduced by a declaration whose declarator is a function declarator of the form:
ptr-declarator ( parameter-declaration-clause ) noexcept-specifier attribute-specifier-seq
Where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms:"
In the case of a member-declaration within a class template, the id-expression must now be the injected class name of the immediately-enclosing entity.
Hence, while C 17 allowed S
Therefore, the error encountered on GCC trunk with -std=c 20 is not a bug but an indication of the breaking change introduced in C 20. Compilers that have not yet implemented this change will continue to compile the old code successfully, while those that have implemented it will adhere to the new requirement.
The above is the detailed content of Can C 20 Class Template Constructors Omit Redundant Template Parameter Lists?. For more information, please follow other related articles on the PHP Chinese website!