在C++中定义类枚举值的std::向量的缩写语法



由于我无法找到答案或正确的单词,我在这里询问:

我有一个由定义的(冗长的(类枚举

enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };

我所知道的定义这些向量的唯一方法是:

#include <vector>
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
int main() {
std::vector<SomeLongName> v1 = {
SomeLongName::Foo,
SomeLongName::FooBar
};
return 0;
}

有没有一种方法(替代缩写语法(可以使用class enum,而不需要为每个值独立重写SomeLongName::例如类似(不起作用(的东西

#include <vector>
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
int main() {
std::vector<SomeLongName> v1 = (SomeLongName::) { Foo , Bar };
return 0;
}

如果这很重要:我正在使用MSVC 2019,amd64(64位(,windows 10上的C++17 64位

注意:使用这个stackerflow讨论线程中建议的typedef实际上不是我想要或要求的

C++20使用enum X语法添加,它看起来就是这样。

#include <vector>
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
int main()
{
using enum SomeLongName;
std::vector<SomeLongName> v1 = { Foo, Bar };
return 0;
}

在以前的版本中,可以使用枚举而不是枚举类。

Pre C++20:不幸的是没有;特征";您必须在作用域枚举的前面加上枚举类型的名称。然而,在作用域枚举成为一种东西之前,通常将枚举封装在类中以避免污染命名空间。你仍然可以这样做:

#include <vector>
struct SomeLongName {
enum values { Foo = 1,Bar = 7, FooBar = 42};
static std::vector<values> make_vect() {
return {Foo,FooBar};
}
};
int main() {
auto v = SomeLongName::make_vect();
}

这不是";漂亮的";但它是有效的。

过去的C++20:我请你参考这个答案。

最新更新