2017-09-15 146 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> 
{ 

};