typedef inheritance from a pure abstract base
Asked Answered
H

1

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?

Hibachi answered 3/9, 2010 at 20:21 Comment(3)
no, you cannot do that directly. you can however make up a macro which will do that.Lowboy
possible duplicate of Inheritance and templates in C++ - why are methods invisible?Riker
Possible duplicate of Propagating 'typedef' from based to derived class for 'template'Mcarthur
L
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.

Lowboy answered 3/9, 2010 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.