Home >Backend Development >C++ >How to Explicitly Invoke Template Constructors in C Initializer Lists?

How to Explicitly Invoke Template Constructors in C Initializer Lists?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 08:28:10725browse

How to Explicitly Invoke Template Constructors in C   Initializer Lists?

Explicit Invocation of Template Constructors in Initializer Lists

In C , how can explicit template constructors be invoked when initializing objects within a class constructor? Consider the following example:

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

struct U {
    U() : t<void>() {} // This approach does not work
    T t;
};

Problem Statement

The provided code attempts to explicitly invoke the template constructor of T within the initializer list of U. However, this approach fails.

Answer

Explicitly invoking template constructors in initializer lists is not supported in C . This limitation stems from the fact that template arguments are typically specified after the function template name using angle brackets. Since constructors do not have their own names, there is no conventional way to pass template arguments to them.

Explanation

The C standard explicitly notes this limitation in section 14.8.1/7:

[Note: 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. ]

Workarounds

One workaround is to utilize a helper type to pass the template argument as an argument to a constructor that accepts a type identity. For example:

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

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

In this case, the identity template defined in Boost can be used to wrap the template argument. Alternatively, in C 20, the std::type_identity type can be used.

Reference

  • [std::type_identity](https://en.cppreference.com/w/cpp/types/type_identity)

The above is the detailed content of How to Explicitly Invoke Template Constructors in C Initializer 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