从纯抽象基类继承typedef

时间:2010-09-03 20:21:14

标签: c++ design-patterns inheritance typedef template-method-pattern

修改:找到 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限定派生ConcreteTemplateMethodtypename TemplateMethod< Analyzer<T> >::system_t&的类型名称,但这有点冗长,我想避免重新每次我继承并且需要使用相同的typedef时,system_t到基地。我可以在基础TemplateMethod中定义吗?

1 个答案:

答案 0 :(得分:8)

你应该做

typedef typename TemplateMethod<X>::system_t system_t;

到“继承”typedef。 typedef不会自动继承(如果编译符合规)。

如果你仔细查看堆栈溢出,那么这个问题就会出现重复。