【发布时间】:2013-01-22 20:30:59
【问题描述】:
下一个代码运行良好(这是我的其他问题的过度简化版本,类型更长、更深、模板更多):
template<class C>
struct Base
{};
template<class C>
struct Derived : public Base<C>
{
Derived() : Base<C>()
{}
};
但是,如果不“写入”其基类的完整类型,我怎么能调用基类构造函数呢?例如,我尝试过类似的方法:
template<class C>
struct Base
{
typedef Base base_type;
};
template<class C>
struct Derived : public Base<C>
{
Derived() : base_type() {}
};
int main()
{
Derived<void> b;
}
但“base_type”无法识别。 gcc 抛出的消息是:
test3.cpp: In constructor 'Derived<C>::Derived()':
test3.cpp:100:17: error: class 'Derived<C>' does not have any field
named 'base_type'
为了解决这个问题,我必须在构造函数中写入Base<C>::base_type,但这会使base_type 本身的存在变得无关紧要。
难道我的省写运动不可能吗?
而且,为什么没有找到构造函数中的base_type,但它工作正常?
int main()
{
Derived<void>::base_type b;
}
编辑:在@Jack Aidley 的评论中,我发现使用简单别名获取基类类型的最佳形式是:
template<typename C> struct Base {};
template<typename C, typename Base>
struct Derived_impl : public Base
{
Derived_impl() : Base()
{}
};
template<typename C>
using Derived = Derived_impl<C, Base<C> >;
int main()
{
Derived<void> b;
}
【问题讨论】:
-
有什么理由不能做
template<class C, class Base> struct Derived : public Base<C>? -
这似乎是个好主意。谢谢。
标签: c++ templates inheritance