2017-06-14 192 views
0

我試圖理解爲什麼下面的代碼不會編譯:如何管理一組派生類枚舉而不需要實例化派生類?

template <class Derived> struct Base { 
    const std::set<typename Derived::Foo> types() const { return theSet; } 
    std::set<typename Derived::Foo> theSet; 
}; 

struct Derived : Base<Derived> { 
    enum Foo { X,Y,Z }; 
}; 

int main(int argc, char** argv) { Derived x; return 0; } 

我得到一個錯誤說,與types() const行是無效的使用不完全struct Derived - 但它需要知道一切該集的類型是一個Foo枚舉,所以我不知道我明白這個錯誤,或者如果有一種方法,它不需要我使這一套類型int ..

完整的錯誤從編譯器說:

error: invalid use of imcomplete type 'struct Derived' 
    const std::set<typename Derived::Foo> types() const { 
error: forward declaration of 'struct Derived' 
struct Derived : Base<Derived> 
+0

總是有幫助的,包括在您的文章 –

+0

實際的錯誤信息,我想,當編譯器試圖實例化派生類它看到,它是由基地衍生和instatiates它。但此時Derived沒有完全實例化,所以編譯器不知道Derived :: Foo的類型是什麼(std :: set不能用不完整的模板參數實例化)。 –

+0

@DmitryGordon有沒有簡單的方法呢?我擔心我可能不得不使用整數集... –

回答

0

要編譯這個例子中,編譯器將需要爲嵌套類型預先聲明這並不似乎是可能的(見How do I forward declare an inner class?),因此最簡單的解決方法可能是讓Base班採取兩種模板和移動Foo你的類定義的:

#include <set> 

template <class T, typename F> struct Base 
{ 
    const std::set<F> types() const { return theSet; } 
    std::set<F> theSet; 
}; 

enum class Foo { X,Y,Z }; 

struct Derived : Base<Derived, Foo> 
{ 
}; 

int main(int argc, char** argv) 
{ 
    Derived x; return 0; 
}