1

I have a child class (Child) that inherits a base class (Base) templated on the child class. The child class is also template on a type (can be integer or whatever ...), and I'm trying to access this type in the base class, I tryed a lot of stuff without success ... here is what I think might be the closer to a working solution, but it doesn't compile ...

template<typename ChildClass>
class Base
{
    public: 
        typedef typename ChildClass::OtherType Type;

    protected:
        Type test;
};

template<typename TmplOtherType>
class Child
    : public Base<Child<TmplOtherType> >
{
    public:
        typedef TmplOtherType OtherType;
};

int main()
{
    Child<int> ci;
}

here is what gcc tells me:

test.cpp: In instantiation of ‘Base >’: test.cpp:14:7:
instantiated from ‘Child’ test.cpp:23:16: instantiated from here test.cpp:7:48: error: no type named ‘OtherType’ in ‘class Child’

Here is a working solution that is equivalent :

template<typename ChildClass, typename ChildType>
class Base
{
    public:
        typedef ChildType Type;

    protected:
        Type test;
};

template<typename TmplOtherType>
class Child 
    : public Base<Child<TmplOtherType>, TmplOtherType>
{
    public:
};

But what bothers me is the repetitive template parameter (forwarding the TmplOtherType as Childtype) to the base class ...

What do you guys think ?

b3nj1
  • 667
  • 1
  • 6
  • 17

1 Answers1

2

You could use template template parameter to avoid repetitive template arguments:

template<template<typename>class ChildTemplate, //notice the difference here
          typename ChildType>
class Base
{
  typedef ChildTemplate<ChildType>  ChildClass; //instantiate the template
  public:
    typedef ChildType Type;

  protected:
    Type test;
};

template<typename TmplOtherType>
class Child 
    : public Base<Child, TmplOtherType> //notice the difference here also
{
    public:
};
Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    Well you are the man, it works like magic ;) Btw I didn't know about template template parameter, awesome ! Thx ! – b3nj1 Sep 19 '12 at 09:18