Home >Backend Development >C++ >How to Explicitly Invoke Template Constructors in C 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; };
The provided code attempts to explicitly invoke the template constructor of T within the initializer list of U. However, this approach fails.
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.
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. ]
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.
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!