编辑:发现 duplicate
我已将一些问题代码缩减为最简单的工作案例以说明以下内容:我在纯抽象基类中的 typedef 未被派生类继承。在下面的代码中,我想继承 system_t
typedef 到 ConcreteTemplateMethod
:
#include <iostream>
// pure abstract template-method
template <typename T> // T == Analyzer<U>
class TemplateMethod {
public:
typedef T system_t;
virtual void fn (const system_t& t) const = 0;
};
template <typename T>
class Analyzer {
public:
void TemplatedAlgorithm (const TemplateMethod< Analyzer <T> >& a) const {
printf ("Analyzer::TemplatedAlgorithm\n");
a.fn(*this); // run the template-method
}
void fn () const {
printf ("Analyzer::fn\n");
}
};
// concrete template-method
template <typename T>
class ConcreteTemplateMethod : public TemplateMethod < Analyzer<T> > {
public:
typedef Analyzer<T> system_t;
virtual void fn (const system_t& t) const {
printf ("ConcreteTemplateMethod::fn\n");
t.fn(); // perform Analyzer's fn
}
};
int main () {
Analyzer <double> a;
ConcreteTemplateMethod<double> dtm;
a.TemplatedAlgorithm(dtm);
return 0;
}
此代码按预期编译和运行。在ConcreteTemplateMethod
以下是必需的,删除后会导致编译器错误:
typedef Analyzer<T> system_t;
请注意 system_t
类型已经是 typedef
但是,在基类中编辑。为什么在继承时必须包含另一个 typedef?
我意识到我可以限定 system_t
的类型名在派生ConcreteTemplateMethod
通过使用 typename TemplateMethod< Analyzer<T> >::system_t&
,但这有点冗长,我想避免不得不重新 typedef
每次我继承并需要使用相同的 system_t
时到基地.我可以在基础 TemplateMethod
中定义解决这个问题的方法吗? ?
最佳答案
你应该做的
typedef typename TemplateMethod<X>::system_t system_t;
“继承”typedef。 typedef 不会自动继承(如果编译器兼容)。
如果你查看堆栈溢出,这个问题会在某处重复。
关于c++ - 从纯抽象基类继承 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3639340/