4

Why does the following not 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 is that Base cannot access its Child's Type? I tried the same with a static function instead of a typedef, and that works just fine.

I tried both GCC 4.4.2 and clang 3.0.

Oliver Zheng
  • 7,831
  • 8
  • 53
  • 59
  • Possible duplicate of [C++ static polymorphism (CRTP) and using typedefs from derived classes](http://stackoverflow.com/questions/6006614/c-static-polymorphism-crtp-and-using-typedefs-from-derived-classes) – George Hilliard Aug 01 '16 at 14:24

2 Answers2

1

That kind of code won't work because Derived is not fully defined yet at the point in which Base is instantiated. It'll basically be an incomplete type.

Alternatives can range from simple to very complex. Probably the simplest way, if you can do it, is to avoid working with Child::Type until you actually need it (lazy evaluation, essentially). It would help if you state exactly what you want to achieve.

stinky472
  • 6,737
  • 28
  • 27
1

In completement to stinky472 answer, if you base is dependant on having Type, then you could do a lot worse than

template<typename Child, typename Type>
struct base
{
     Type t;
};

   struct Derived : public Base<Derived, int>
{
};

It's not as clean though.

111111
  • 15,686
  • 6
  • 47
  • 62