Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRTP refer to typedef in derived class from base class

I have following code:

template <typename T>
class A
{
    typedef typename T::Type MyType;
};

template <typename T>
class B : public A<B<T>>
{
    typedef T Type;
};

When I try to instantiate B, I get following error message using MSVS 2015:

'Type': is not a member of 'B<int>'

Is this code valid C++ or is MSVS right?

like image 922
Alexander Bily Avatar asked Mar 28 '16 18:03

Alexander Bily


1 Answers

The problem is at this point

template <typename T>
class A
{
    typedef typename T::Type MyType;
                     ^^^
};

T needs to be a complete type. But in your case, when A<T> is instantiated here:

template <typename T>
class B : public A<B<T>>
                 ^^^^^^^

B<T> is not yet a complete type! So this cannot work unfortunately.

The simple solution is just to pass in Type separately:

template <typename T, typename Type>
class A
{
    typedef Type MyType;
};    

template <typename T>
class B : public A<B<T>, T>
{

};
like image 139
Barry Avatar answered Sep 21 '22 01:09

Barry