编辑:找到 复制

我将一些问题代码缩减为最简单的工作案例,以说明以下内容:纯抽象基类中的Typedef并未由派生类继承。在下面的代码中,我想继承 system_t 打字到 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不会自动继承(如果编译器符合编译器)。

如果您浏览堆栈溢出,将会在某个地方重复此问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top