Andrew Spott
Andrew Spott

Reputation: 3637

Changing type signature of base class member based on inheriting class template

I have two classes, one inherits from another:

struct A {
    (pure?) virtual tt returns_something();
}

template <typename T>
struct B : A {
    virtual T returns_something();
}

How do I make this work, such that returns_something() has the right type signature.

I believe this is a job for the curiously recurring template pattern:

template <typename T>
struct A {
    pure virtual typename T::tt returns_something();
}
template <typename TT>
struct B : A<B<TT>> {
    typedef TT tt;
    virtual tt returns_something();
}

However, this seems to complain that "there is no type named 'tt' in B< float >" (when I instantiate B with TT as a float).

Any ideas? Is this the right approach in this case? Is there another approach that is better suited?

note: This is a simplified situation. Templating A on the same type B is templated on just makes A have lots of template parameters, and I don't want that.

Upvotes: 0

Views: 38

Answers (1)

T.C.
T.C.

Reputation: 137425

At the time A<B<TT>> is instantiated, B<TT> is still an incomplete class, so you can't use B<TT>::tt.

If the type at issue is a template argument of B, then you can extract the template parameter via a traits class:

template <typename TT>
struct B;

template<class> struct B_traits;
template<class TT> 
struct B_traits<B<TT>> {
    using tt = TT;
};

template <typename T>
struct A {
   virtual typename B_traits<T>::tt returns_something();
};

Demo.

Upvotes: 2

Related Questions