如何在不需要实例化派生的 class 的情况下管理一组派生的 class 枚举?

How can i manage a set of derived class enums without needing to instantiate the derived class?

我正在尝试了解为什么以下代码片段无法编译:

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 enum 所以我不确定我是否理解错误或者是否有解决方法不需要我制作那组类型 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>

要编译此示例,编译器需要嵌套类型的前向声明,这似乎是不可能的(请参阅 How do I forward declare an inner class?),因此最简单的解决方法可能是 Base class使用两个模板并将 Foo 移出您的 class 定义:

#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;
}