只是好奇,是否有可能从模板类继承并在派生类的构造函数中调用基类的构造函数,该基类也是模板化的并且没有参数可从中推断其类型?
template<typename T>
struct Base {
template<typename D>
Base() { // no argument of type D to infer from
static_assert(std::is_same<T,D>::value, "");
}
};
struct Derived : Base<int> {
Derived() : Base<int>::Base<int>() {} // is there a way to write it correctly?
};
在我的特定情况下,我可以用模板方法替换模板构造函数,但这仍然是一个关于语言灵 active 的有趣问题。
最佳答案
C++ 标准对此有何规定(第 14.8.1 节):
[ 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. — end note ]
这是一个注释,而不是规则,因为它实际上是其他两个规则的结果,一个在同一部分:
Template arguments can be specified when referring to a function template specialization by qualifying the function template name with the list of template-arguments in the same way as template-arguments are specified in uses of a class template specialization.
从 12.1 开始
Constructors do not have names.
关于c++ - 派生自模板基类的模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553803/