Home >Backend Development >C++ >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; };
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; };
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; };
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!