【发布时间】:2014-10-24 18:11:47
【问题描述】:
只是好奇,是否有可能从模板类继承并在派生类的构造函数中调用基类的构造函数,该基类也是模板化的并且没有参数来推断其类型?
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?
};
在我的特殊情况下,我可以用模板方法替换模板构造函数,但这仍然是一个关于语言灵活性的有趣问题。
【问题讨论】:
-
不可能为构造函数显式指定模板参数。所以不,你不能那样做。
-
看起来很偏执(确保派生类正确使用基类)
-
如果您认为 Base 类使用编译时信息来为其构造选择不同的操作,则不是这样。
标签: c++ templates inheritance c++11