我有一个子类(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&gt;'的实例化中:test.cpp:14:7:
从'Child'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)到基类......
你们觉得怎么样?
答案 0 :(得分:2)
您可以使用template template parameter来避免重复的模板参数:
template<template<typename>class ChildTemplate, //notice the difference here
typename ChildType>
class Base
{
typedef ChildTemplate<ChildType> ChildClass; //instantiate the template
public:
typedef ChildType Type;
protected:
Type test;
};
template<typename TmplOtherType>
class Child
: public Base<Child, TmplOtherType> //notice the difference here also
{
public:
};