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

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

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

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

有没有办法(替代缩写语法)使用 aclass enum并且不需要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

注意:使用像在这个 stackoverflow 讨论线程中建议的 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;
}

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


以上是在C++中定义类枚举值的std::vector的缩写语法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>