Home > Backend Development > C++ > Is Redundant Template Parameter Listing in C 20 Class Template Constructors Allowed?

Is Redundant Template Parameter Listing in C 20 Class Template Constructors Allowed?

DDD
Release: 2024-11-26 06:54:10
Original
834 people have browsed it

Is Redundant Template Parameter Listing in C  20 Class Template Constructors Allowed?

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>();
};
Copy after login

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>();
                 ^
Copy after login

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.
...
Copy after login

Essentially, the "redundant" template parameter list, S(), used in the previous code is no longer permitted. Instead, the injected class name, S, must be used:

template<typename T>
struct S {
    S(); // CORRECT C++20 syntax
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template