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

标签 c++ enums

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

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

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/

相关文章:

c++ - UTF-8 表示形式和 unicode 表示形式之间的字符串转换

c++ - GDB 无法访问 mmap() 的内核分配内存?

header 中缺少 C++ ODBC SQL_ATTR_PARAMS_STATUS_PTR

c++ - 为什么无法识别我重载的乘法运算符?

java - JNI- FindClass 函数返回 null

ruby-on-rails - 从表单中选择枚举以设置角色

ios - 为什么我在 Swift 中设置时 Enum 的值没有改变?

yii - 如何进行字段枚举迁移 yii2

c# - 枚举参数在 C# 中可以是可选的吗?

mysql - 枚举 ('active' ,'inactive' ) 与枚举(0,1)