Home >Backend Development >C++ >Why Can\'t I Explicitly Invoke Template Constructors in C Initializer Lists?
In C , it is not possible to explicitly invoke a template constructor within an initializer list. Consider the following example:
struct T { template<class> T(); }; struct U { U() : t<void>() {} //does not work T t; };
This code will fail to compile, as the C Standard explicitly disallows explicit template argument lists for constructor member function templates. This is due to the unique syntax of constructors, which do not have a function name.
Explanation: The C Standard states in Section 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."
Workaround: If the explicit invocation of a template constructor is necessary within an initializer list, a workaround can be employed using a custom type with a constructor that accepts the template parameters as an argument:
struct T { template<class U> T(identity<U>); }; struct U { U() : t(identity<void>()) {} T t; };
In this case, the identity type from the Boost library or the std::type_identity from C 20 can be used to represent the template parameter type. This allows the template constructor to be invoked indirectly using an object of this custom type.
The above is the detailed content of Why Can\'t I Explicitly Invoke Template Constructors in C Initializer Lists?. For more information, please follow other related articles on the PHP Chinese website!