2017-06-14 190 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; 
}