【发布时间】:2012-09-19 08:58:01
【问题描述】:
我有一个子类 (Child),它继承了以子类为模板的基类 (Base)。子类也是一个类型的模板(可以是整数或其他......),我试图在基类中访问这个类型,我尝试了很多东西但没有成功......这就是我的想法可能更接近可行的解决方案,但无法编译...
template<typename ChildClass>
class Base
{
public:
typedef typename ChildClass::OtherType Type;
protected:
Type test;
};
template<typename TmplOtherType>
class Child
: public Base<Child<TmplOtherType> >
{
public:
typedef TmplOtherType OtherType;
};
int main()
{
Child<int> ci;
}
这是 gcc 告诉我的:
test.cpp:在“Base >”的实例化中:test.cpp:14:7:
从“子”实例化 test.cpp:23:16: 实例化自 这里 test.cpp:7:48: 错误: 在“类”中没有名为“OtherType”的类型 孩子”
这是一个等效的工作解决方案:
template<typename ChildClass, typename ChildType>
class Base
{
public:
typedef ChildType Type;
protected:
Type test;
};
template<typename TmplOtherType>
class Child
: public Base<Child<TmplOtherType>, TmplOtherType>
{
public:
};
但困扰我的是重复的模板参数(将 TmplOtherType 作为 Childtype 转发)到基类...
你们怎么看?
【问题讨论】:
标签: c++ templates generics typedef typename