首页 > 解决方案 > 是否有建议让 c++ 将上下文用于短枚举值?

问题描述

enum class在我们的代码中到处使用。有时,命名空间会堆积起来,使代码的可读性降低:

_infoSign->setType(ui::InfoSign::Type::Ok);

我知道,我可以用一个using声明来缩短它:

using Type = ui::InfoSign::Type;
_infoSign->setType(Type::Ok);

using语句的缺点是自己的定义Type。如果enum名称更改为Foo,此代码将保留Type名称并且必须手动更新。

Swift 使用一种有趣的方式来处理枚举值:

enum CompassPoint {
    case north
    case south
    case east
    case west
}

func foo(dir: CompassPoint) {
    // ...
}

对于函数调用,编译器将自动使用正确的上下文并允许使用非常短的形式来指定枚举值:

foo(.north)

是否有针对类似语法的 C++ 提案?

标签: c++enumsnamespacesc++20

解决方案


我所知道的正是这种情况下没有类似的提议。也就是说,为了减少初始化作用域枚举器的噪音。它在风格上似乎与指定的初始化程序(C++20 的新功能)相似,但有点反对作用域枚举器是......你知道的,作用域的想法。


枚举类更常见的问题是 switch 语句中的冗长。对于那个问题,有P1099: Using Enum,它减少了

std::string_view to_string(rgba_color_channel channel) {
  switch (channel) {
    case rgba_color_channel::red:   return "red";
    case rgba_color_channel::green: return "green";
    case rgba_color_channel::blue:  return "blue";
    case rgba_color_channel::alpha: return "alpha";
  }
}

std::string_view to_string(rgba_color_channel channel) {
  switch (my_channel) {
    using enum rgba_color_channel;
    case red:   return "red";
    case green: return "green";
    case blue:  return "blue";
    case alpha: return "alpha";
  }
}

我想你也可以写:

using enum ui::InfoSign::Type;
_InfoSign->SetType(Ok);

但这并没有真正减少冗长(除非您在同一范围内多次执行该操作)。


推荐阅读