4

I don't understand the following code:

template <int _id> class Model;

template <int _id> class Model : public Model<0> { ... };

So, class Model derives from itself it seems. This doesn't compile with EDG or Gcc (error: invalid use of incomplete type ‘class Model<0>’), but Visual Studio accepts it. What compiler is right and for what reason?

Paul Jansen
  • 1,216
  • 1
  • 13
  • 35
  • Also see [How can a class inherit from a template based on itself?](https://stackoverflow.com/q/8336220/608639) – jww Dec 15 '18 at 11:30

2 Answers2

7

So, class Model derives from itself it seems.

The class doesn't inherit itself. Every instatiation of Model<N> is a different, unrelated class.

This doesn't compile with EDG or Gcc (error: invalid use of incomplete type ‘class Model<0>’), but Visual Studio accepts it. What compiler is right and for what reason?

GCC is correct, at the point of usage, Model<0> is incomplete. Inheritance requires a complete class declaration.

user0042
  • 7,917
  • 3
  • 24
  • 39
1

What compiler is right and for what reason?

Microsoft's compilers differ from clang and gcc in the way they handle template expansion (cf "two phase lookup").

The gcc implementation is closer to the standard.

If you want all models to have the characteristics of Model<0> then I think I would defer the common code to a different base class, which could itself be a template of course.

e.g.

template <class Outer, int _id> class ModelImpl
{
    void modelly_thing() {};
};

template <int _id> class Model 
: public ModelImpl<Model<_id>, 0> 
{

};
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142