Redundant Template Parameter Lists in Class Template Constructors in C 20
The validity of class template constructors having redundant template parameter lists has been debated since the introduction of C 20. Here's the issue and its resolution:
In C 17, the code below was considered well-formed:
template<typename T> struct S { S<T>(); };
However, in C 20, the same code triggers an error in some compilers (e.g., gcc trunk) under -std=c 20:
error: expected unqualified-id before ')' token 3 | S<T>(); ^
Change in C 20
The C 20 standard mandates a change in the syntax of class template constructor declarations. The following delta in the standard's compatibility section highlights this:
[diff.cpp17.class] ... Change: A simple-template-id is no longer valid as the declarator-id of a constructor or destructor. Rationale: Remove potentially error-prone option for redundancy. ...
Essentially, the "redundant" template parameter list, S
template<typename T> struct S { S(); // CORRECT C++20 syntax };
Rationale
The rationale for this change is to reduce the risk of errors by disallowing the use of simple template IDs. By enforcing the explicit use of the injected class name, the compiler can more accurately resolve the intended constructor.
Conclusion
This change in C 20 does not constitute a bug, but rather an intentional breaking change to enhance the clarity and correctness of class template constructor declarations. While this may cause compatibility issues with existing code relying on the previous syntax, it ultimately improves the overall safety and reliability of C applications.
The above is the detailed content of Is Redundant Template Parameter Listing in C 20 Class Template Constructors Allowed?. For more information, please follow other related articles on the PHP Chinese website!