2017-09-15 142 views
1

我不明白下面的代码:类如何继承自己?

template <int _id> class Model; 

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

所以,类模型从自身派生它似乎。这不会与EDG或Gcc编译(错误:使用不完整类'类型< 0>'),但Visual Studio接受它。什么编译器是正确的,出于什么原因?

回答

5

So, class Model derives from itself it seems.

类不继承本身Model<N>的每个instatiation是一个不同的,不相关的类。

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是正确的,在使用点,Model<0>是不完整的。继承需要完整的类声明。

0

What compiler is right and for what reason?

微软的编译器在处理模板扩展的方式上不同于clang和gcc(参见“两阶段查找”)。

gcc实现更接近标准。

如果你想要所有的模型具有Model<0>的特性,那么我想我会推迟到一个不同的基类,这本身可以是一个模板当然。

例如

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

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

};