Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在不需要实例化派生类的情况下管理一组派生类枚举?_C++_Templates_Inheritance_Gcc_Crtp - Fatal编程技术网

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

C++ 如何在不需要实例化派生类的情况下管理一组派生类枚举?,c++,templates,inheritance,gcc,crtp,C++,Templates,Inheritance,Gcc,Crtp,我试图理解为什么以下代码段无法编译: 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

我试图理解为什么以下代码段无法编译:

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

要编译此示例,编译器将需要一个嵌套类型的前向声明,这似乎是不可能的(请参阅),因此最简单的解决方法可能是使
Base
class获取两个模板,并将
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;
}
#包括
模板结构基
{
const std::set types()const{return theSet;}
std::设置主题集;
};
枚举类Foo{X,Y,Z};
派生结构:基
{
};
int main(int argc,字符**argv)
{
派生x;返回0;
}

在POST中包含实际的错误消息总是很有帮助的。假设编译器试图实例化派生类时,它看到它是从基派生的,并对其进行初始化。但是现在派生的还没有完全实例化,所以编译器不知道派生的::Foo是什么类型(std::set不能用不完整的模板参数实例化)。@DmitryGordon有简单的方法解决这个问题吗?我担心我可能不得不将集合设置为int…@CaptainObvlious补充道,模板参数和外部类型不能使用相同的名称。你确定你在给我们看全部代码吗?
#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;
}