Explicit Template Constructor Invocation in C
In C , it is not possible to invoke a template constructor explicitly in an initializer list. This is due to the specific syntax used for template arguments, which follow the function template name rather than being included in the parentheses during construction.
As stated in the C Standard (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. ]
Therefore, the following example will not work:
struct T { template<class> T(); }; struct U { U() : t<void>() {} //does not work T t; };
In this case, the compiler will attempt to interpret t
Workaround
To work around this limitation, one can use a function template that takes an identity type as an argument:
struct T { template<class U> T(identity<U>); }; struct U { U() : t(identity<void>()) {} T t; };
Given the following definition of identity from Boost:
template<typename T> struct identity { typedef T type; };
or, in C 20, using std::type_identity:
using ::std::type_identity;
this approach effectively allows passing template arguments to constructors in initializer lists.
The above is the detailed content of Why Can\'t I Explicitly Invoke a Template Constructor in a C Initializer List?. For more information, please follow other related articles on the PHP Chinese website!