Access to typedef for children from a template parent

Why doesn't the following compile?

template <typename Child> struct Base { typename Child::Type t; // Does not compile. "No type named Type in Child" }; struct Derived : public Base<Derived> { typedef int Type; }; 

How can this Base not access its Child type? I tried the same with a static function, not a typedef, and this works fine.

I tried both GCC 4.4.2 and clang 3.0.

+4
source share
2 answers

Such code will not work because Derived is not yet fully defined at the point at which the Basis is created. Basically it will be an incomplete type.

Alternatives can range from simple to very complex. Probably the easiest way if you can do this is to avoid working with Child :: Type until you need it (lazy evaluation, essentially). This will help if you specify exactly what you want to achieve.

+1
source

In addition to stinky472's request, if you base are type dependent, then you can do a lot worse than

 template<typename Child, typename Type> struct base { Type t; }; struct Derived : public Base<Derived, int> { }; 

It is not so clean though.

+1
source

Source: https://habr.com/ru/post/1399478/


All Articles