Home > Backend Development > C++ > Can Explicit Template Constructors Be Invoked Using Initializer Lists?

Can Explicit Template Constructors Be Invoked Using Initializer Lists?

Mary-Kate Olsen
Release: 2024-12-02 16:56:10
Original
843 people have browsed it

Can Explicit Template Constructors Be Invoked Using Initializer Lists?

How To Invoke Explicit Template Constructors Using Initializer Lists

Question:

Can explicit template constructors be invoked using initializer lists, as seen in the following example?

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

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

Answer:

Unfortunately, it is not possible to explicitly invoke template constructors using initializer lists.

According to the C Standard at 14.8.1/7, "[...] 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 constructors, which lack their own names, cannot accept template arguments explicitly. In your case, the compiler interprets t as a base-class type, causing the code to fail.

To address this issue, you can employ a workaround:

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

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

Here, identity acts as a placeholder for the template parameter. Within C 20, you can use std::type_identity as identity type.

The above is the detailed content of Can Explicit Template Constructors Be Invoked Using Initializer Lists?. 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