c++ - 是否有建议让 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++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);
但这并没有真正减少冗长(除非您在同一范围内多次执行该操作)。
推荐阅读
- php - 错误:SQLSTATE[HY093]:无效参数号:未定义参数 NOOB
- laravel - 雄辩的 hasOne 关系返回 null
- docker - Openshift/original - 基于 Wildfly 创建镜像
- python - 为什么 cookie(显示在 Postman 应用程序中)没有显示在 Python 响应变量中?
- python - 将二进制搜索解决方案与书籍进行比较
- javascript - React 表单提交 - 字段始终为空
- android - 带背景和形状的按钮没有按下效果
- r - 按列减去数据帧的行,保留多因子列
- c# - 油门 - 最多每 N 毫秒调用一次函数?
- django - 我无法更改 django drf 中的日期格式