Home >Backend Development >C++ >Can C 20 Class Template Constructors Omit Redundant Template Parameter Lists?

Can C 20 Class Template Constructors Omit Redundant Template Parameter Lists?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 15:12:03400browse

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() as a constructor declaration within the template S, C 20 requires S() instead. This change effectively removes the redundancy and aligns with CWG 2237, which addresses potential error-prone practices.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn