8

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?

Community
  • 1
  • 1
Shamster
  • 2,092
  • 5
  • 24
  • 27
  • no, you cannot do that directly. you can however make up a macro which will do that. – Anycorn Sep 03 '10 at 21:03
  • possible duplicate of [Inheritance and templates in C++ - why are methods invisible?](http://stackoverflow.com/questions/1567730/inheritance-and-templates-in-c-why-are-methods-invisible) – David Rodríguez - dribeas Sep 03 '10 at 23:23
  • Possible duplicate of [Propagating 'typedef' from based to derived class for 'template'](https://stackoverflow.com/questions/1643035/propagating-typedef-from-based-to-derived-class-for-template) – VLL May 09 '18 at 13:17

1 Answers1

8

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.

Anycorn
  • 50,217
  • 42
  • 167
  • 261