Search code examples
c++templatesmetaprogramming

Can the type of a base class be obtained from a template type automatically?


I am trying to use template meta-programming to determine the base class. Is there a way to get the base class automatically without explicitly specializing for each derived class?

class foo { public: char * Name() { return "foo"; }; };
class bar : public foo { public: char * Name() { return "bar"; }; };

template< typename T > struct ClassInfo { typedef T Base; };
template<> struct ClassInfo<bar> { typedef foo Base; };

int main()
{
  ClassInfo<foo>::Base A;
  ClassInfo<bar>::Base B;

  std::cout << A.Name();  //foo
  std::cout << B.Name();  //foo
}

for right now any automatic method would need to select the first declared base and would fail for private bases.


Solution

  • My solutions are not really automatic, but the best I can think of.

    Intrusive C++03 solution:

    class B {};
    
    class A : public B
    {
    public:
        typedef B Base;
    };
    

    Non-intrusive C++03 solution:

    class B {};
    
    class A : public B {};
    
    template<class T>
    struct TypeInfo;
    
    template<>
    struct TypeInfo<A>
    {
        typedef B Base;
    };