Home  >  Article  >  Backend Development  >  Why Are Redundant Template Parameter Lists in C 20 Class Template Constructors Now an Error?

Why Are Redundant Template Parameter Lists in C 20 Class Template Constructors Now an Error?

DDD
DDDOriginal
2024-11-19 06:32:02463browse

Why Are Redundant Template Parameter Lists in C  20 Class Template Constructors Now an Error?

Redundant Template Parameter Lists in Class Template Constructors in C 20

In C , the syntax for declaring constructors in class templates has undergone a change in C 20. Previously, code of the following form was considered well-formed:

template<typename T>
struct S {
    S<T>();
};

Despite the redundancy of the template parameter in the constructor declaration, this code compiled successfully. However, in C 20 with the -std=c 20 flag enabled, GCC trunk now reports an error for this code:

error: expected unqualified-id before ')' token
3 |     S<T>();
^

While this error is not encountered in GCC10.2 or Clang with -std=c 20, it stems from a fundamental change introduced in C 20.

According to the C 20 compatibility section, the use of a simple-template-id as the declarator-id for a constructor or destructor is no longer valid. This move aims to eliminate potential error-prone redundancy.

The new wording in C 20's [class.ctor] section specifies that for constructors in member declarations within class templates, the injected-class-name should be used instead:

template<typename T>
struct S {
    S();  // Use injected-class-name
};

In this example, S represents the injected-class-name for the inner class template. Consequently, the redundant template parameter is removed from the constructor declaration.

The above is the detailed content of Why Are Redundant Template Parameter Lists in C 20 Class Template Constructors Now an Error?. 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