C++ 调用显式模板构造函数

标签 c++ templates

你能告诉我如何显式调用模板构造函数(在初始化列表中)吗? 例如:

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/

相关文章:

容器化 Linux 环境中的 C++ : why does attempting to allocate large vector causes SIGABRT or neverending loop instead of bad_alloc?

c++ - shader.hlsl 文件导致错误?

c++ - 是否可以在 C++ 中匹配递归整数模板参数?

android - 如何从 Java (Android) 以函数指针作为参数调用 C++ 方法

c++ - TBB 并发 vector 是否支持旧的 C 风格循环?

c++ - 为什么 std::void_t 在这种情况下不起作用?

c++ - 模板和函数参数数量相等

c++ - 在 C++ 中实现基于模板的可选类成员的最有效方法?

c++ - 模板<类型名称 A B>

c++ - 如何检测仅使用 cppcheck 从未使用的函数调用的函数?