你能告诉我如何显式调用模板构造函数(在初始化列表中)吗? 例如:
struct T {
template<class> T();
};
struct U {
U() : t<void>() {} //does not work
T t;
};
谢谢
最佳答案
这是不可能的。该标准在 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. ]
解释:这表示:模板参数在函数模板名称后的尖括号中传递,例如 std::make_pair<int, bool>
.并且构造函数没有自己的名称,但它们在各种上下文中滥用它们的类名(因此 U<int>()
意味着:将 <int>
传递给类模板 U
,并通过调用默认构造函数来构造一个对象而不参数)。因此,不能将模板参数传递给构造函数。
在您的例子中,您正试图在成员初始值设定项中传递模板参数。在那种情况下,还有更多问题:它将尝试解析和解释 t<void>
作为基类类型,并认为你想调用基类的默认构造函数。这当然会失败。
如果你能忍受它,你就可以解决它
struct T {
template<class U> T(identity<U>);
};
struct U {
U() : t(identity<void>()) {}
T t;
};
给定identity
就像在 boost 中定义的一样
template<typename T> struct identity { typedef T type; };
在 C++20 中,您可以使用 std::type_identity
作为身份类型。
关于C++ 调用显式模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42300359/