理想情况下,我希望下面的示例能够工作,但我猜其中一些无法在C++中实现。{typedefStrongEnumColor;//notaC++syntaxColorc=Color::Red;//staticconstColord;//error:defaultconstructorisprivateColord=c;Colore=Color::OfInt(5);//ifdefDEBUG-Runtimeerror:Enumoutofrangeintsum=0;//Idohavethesemacros,butseparateforeachenum-FOREACH_COLOR(c)FOREACH
这是来自sec的引述。N3797工作草案3.3.1/4:Givenasetofdeclarationsinasingledeclarativeregion,eachofwhichspecifiesthesameunqualifiedname,—exactlyonedeclarationshalldeclareaclassnameorenumerationnamethatisnotatypedefnameandtheotherdeclarationsshallallrefertothesamevariableorenumerator,orallrefertofunctionsandfun
使用普通枚举,我能够使用以下代码访问Q_ENUMS属性和具体的枚举字符表示://in.hclassEnumClass:publicQObject{Q_OBJECTpublic:enumMyEnumType{TypeA,TypeB};Q_ENUMS(MyEnumType)private:MyEnumTypem_type;};//in.cppm_type=TypeA;...constQMetaObject&mo=EnumClass::staticMetaObject;intindex=mo.indexOfEnumerator("MyEnumType");QMetaEnummetaEnum=
是否有任何方法(可能需要C++11/14)来推断枚举中元素的数量,而不考虑枚举元素本身的值?考虑一个像这样的枚举enum{Val1=1,Val2=2,Val3=4}答案是3。我知道那里有皱纹,我可以在那里Val3=Val1,但对于我的用例可以忽略这一点。我已经在SO和其他地方看到了很多类似的问题,但我还没有找到合适的答案。如果有的话。通常,建议的解决方案是引入一个LAST元素,但这只会给我下一个更高的枚举值(使用上面的例子,那将是5),这对我来说没有用。 最佳答案 Ifthereisanyatall.没有。即使使用新的C++17,据
Cppreference声称,除其他事项外,您可以专注于memberenumerationofaclasstemplate由于没有提供示例,我试图猜测如何做到这一点。我最终得到了以下结果:templatestructA{enumE:int;};templateenumA::E:int{a,b,c};Clang(带有-std=c++17-pedantic-errors的8.0.0)编译它。GCC(9.1with-std=c++17-pedantic-errors)拒绝代码error:templatespecializationof'enumA::E'notallowedbyISOC++[
我正在编写从c到c++类的移植文件io函数集。“魔数(MagicNumber)”(未命名常量)比比皆是。这些函数读取一个文件头,其中包含许多特定条目,其位置当前由魔数(MagicNumber)表示。几年前,一位资深程序员告诉我,使用“魔数(MagicNumber)”本质上是邪恶的,因此,从那以后,我一直试图避免在我的端口中使用未命名的常量。所以我想创建某种存储条目的常量列表。到目前为止,我提出了两个看起来相对安全的解决方案——使用命名空间封闭的常量集或命名空间封闭的枚举。我可以安全地使用任何一种解决方案吗?一个比另一个有什么优势吗?例如选项1namespacehdr_pos{const
我使用了新的C++11“枚举类”类型,并在使用g++时观察到“undefinedreference”问题。这个问题不会发生在clang++中。我不知道是我做错了什么还是g++错误。重现问题的代码是:(4个文件:enum.hpp、enum.cpp、main.cpp和Makefile)//file:enum.hppenumclassMyEnum{val_1,val_2};templatestructFoo{staticconstMyEnumvalue=MyEnum::val_1;};templatestructFoo{staticconstMyEnumvalue=MyEnum::val_2
我在N3936(条款7.2.2)中读到“在范围枚举的声明中不应省略可选标识符”,所以我尝试了以下代码(嵌入的评论试图解释我的解释)GNU-g++4.8.3和clang3.4.2#includeenumany:int;//unscopedopaquedeclaration:intrequiredbythestandardenum:int{a}t;//unscopedanonymousdeclarationoft(:intnotrequired)enumany:int{b}u;//redlecarationoftype"any"withoneenumeratorenumclassfoo:c
我有以下枚举enumExample:uint8_t{First=1,Second=2,};和一个字符串流:std::stringstreamstream;boost::archive::binary_oarchivear(stream);现在我注意到,如果我序列化一个枚举:arboost序列化4字节(在本例中为0x01、0x00、0x00、0x00)位,而不是uint8_t所需的8位(0x01)。有什么办法可以避免这种情况吗?我的意思是,我知道我可以将该枚举转换为uint8_t,但这种接缝不是很巧妙(如果必须这样做,我必须更改很多东西)。谢谢和问候 最佳答案
从一些C遗留代码中,我得到了一些常量作为int*。在C++部分,我有一个底层类型int的枚举。在单值基础上枚举和int之间的转换有效。但是,int*和enum*之间的转换是不可能的。请参见下面的代码示例。这是为什么?我如何将指向某些int值的指针转换为指向int枚举的指针,反之亦然?我有点希望它能工作,因为单值转换工作并且基础类型是相同的。我读到了Whathappensifyoustatic_castinvalidvaluetoenumclass?但无法确定潜在的无效值是否在此处起作用。inti=3;enumE:int;Ee;e=static_cast(i);//oki=static_