由于我无法找到答案或搜索正确的词,我在这里问:
我有一个(冗长的)类枚举定义为
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
我知道定义这些 vector 的唯一方法是:
#include <vector>
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
int main() {
std::vector<SomeLongName> v1 = {
SomeLongName::Foo,
SomeLongName::FooBar
};
return 0;
}
有没有一种方法(替代缩写语法)可以使用类枚举
并且不需要为每个值独立重写SomeLongName::
? 例如类似(不工作)
#include <vector>
enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };
int main() {
std::vector<SomeLongName> v1 = (SomeLongName::) { Foo , Bar };
return 0;
}
以防万一:我在 Windows 10 64 位上使用 MSVC 2019、amd64(64 位)、C++17
注意:使用 this stackoverflow discussion thread 中建议的 typedef这实际上不是我想要或要求的
最佳答案
C++20 添加了使用枚举 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;
}
在以前的版本中,您可以使用枚举而不是枚举类。
关于c++ - 在 C++ 中定义类枚举值的 std::vector 的缩写语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67500671/