typedef inheritance from a pure abstract base

ぃ、小莉子 提交于 2019-12-12 07:55:44

问题


Edit: Found duplicate

I've whittled down some problem code to the simplest working case to illustrate the following: my typedef in a pure abstract base class is not being inherited by the derived class. In the code below I'd like to inherit the system_t typedef into the 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;
}

This code compiles and runs as expected. In the ConcreteTemplateMethod the following is required, and when removed causes compiler errors:

typedef Analyzer<T> system_t;

Note that the system_t type is already typedef'ed in the base class, however. Why must I include another typedef when inheriting?

I realize that I can qualify the typename of system_t in the derived ConcreteTemplateMethod by using typename TemplateMethod< Analyzer<T> >::system_t&, but that's a bit verbose, and I'd like to avoid having to re-typedef to the base everytime I inherit and need to use that same system_t. Is there a way around this that I can define in the base TemplateMethod?


回答1:


you should do

typedef typename TemplateMethod<X>::system_t system_t;

to "inherit" typedef. typedef is not automatically inherited (if compiler is compliant).

if you look through stack overflow, there will be duplicate of this question somewhere.



来源:https://stackoverflow.com/questions/3639340/typedef-inheritance-from-a-pure-abstract-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!