Home > Backend Development > C++ > How Can I Explicitly Invoke a Template Constructor in a C Initializer List?

How Can I Explicitly Invoke a Template Constructor in a C Initializer List?

Mary-Kate Olsen
Release: 2024-12-03 04:56:12
Original
539 people have browsed it

How Can I Explicitly Invoke a Template Constructor in a C   Initializer List?

Explicit Template Constructor Invocation in C

Invoking a template constructor explicitly in an initializer list can be a challenge in C . Despite the example provided:

struct T { 
    template<class> T();
};

struct U {
    U() : t<void>() {} //does not work
    T t;
};
Copy after login

The approach fails because it attempts to interpret the syntax incorrectly. According to the C Standard (14.8.1/7), "because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates."

This means that it's not possible to pass template arguments to constructors directly. However, a workaround exists:

struct T { 
    template<class U> T(identity<U>);
};

struct U {
    U() : t(identity<void>()) {}
    T t;
};
Copy after login

In this case, the identity type effectively passes the template argument to the constructor through an intermediary.

Alternatively, in C 20 and later, you can use the std::type_identity type:

struct T { 
    template<class U> T(std::type_identity<U>);
};

struct U {
    U() : t(std::type_identity<void>()) {}
    T t;
};
Copy after login

By utilizing these workarounds, you can effectively initialize template constructors explicitly in initializer lists, despite the limitations imposed by the C Standard.

The above is the detailed content of How Can I Explicitly Invoke a Template Constructor in a C Initializer List?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template