[英]enum, classes, namespaces and long names
From what I understand, enums that relates to a class should be declared inside the class, like this: 根据我的理解,应该在类中声明与类相关的枚举,如下所示:
namespace Sensors {
class MySensor {
public:
enum class SensorStatus {
kSensorActive,
kSensorInactive
}
SensorStatus GetCurrentStatus(void);
};
}
The problem I'm having with this, is that it leads to the following code in another part of the program. 我遇到的问题是,它会在程序的另一部分导致以下代码。
Sensors::MySensor::SensorStatus current_status = mySensor.GetStatus();
switch (current_status):
case Sensors::MySensor::SensorStatus::kSensorActive: // 47 characters!
printf("Sensor is active.");
break;
case Sensors::MySensor::SensorStatus::kSensorInactive: // 49 characters!
printf("Sensor is inactive.");
break;
I appreciate that its very clear what kSensorActive
and kSensorInactive
refers to, no ambiguity there. 我很清楚
kSensorActive
和kSensorInactive
所指的内容非常明确,没有歧义。 But if you try to follow a style guide that specifies 80 characters, we end up with a lot of line breaks, which reduces clarity, IMHO. 但是如果你试着遵循指定80个字符的样式指南,我们最终会有很多换行符,这会降低清晰度,恕我直言。 One example of a long line comes if we have a function that takes two different enumerators;
如果我们有一个带两个不同枚举器的函数,就会出现一个长行的例子。
MyFunction(NamespaceA::MyFirstClass::MyFirstEnum::AnEnumerator, NamespaceB::MySecondClass::MySecondEnum::ADifferentEnumerator)
- a whopping 127 characters. MyFunction(NamespaceA::MyFirstClass::MyFirstEnum::AnEnumerator, NamespaceB::MySecondClass::MySecondEnum::ADifferentEnumerator)
- 高达127个字符。
Is it common with these long names or am I missing something? 这些长名字是常见的还是我错过了什么?
To reduce the length without reducing the overall scope clarity you have at least 2 options: 要在不降低整体范围的情况下缩短长度,您至少有两个选择:
using Status = Sensors::MySensor::SensorStatus;
typedef
ie. typedef
即。 typedef Sensors::MySensor::SensorStatus Status2;
Use these inside the scope of this function so it is local and the ambiguous name doesnt spread throughout the code. 在这个函数的范围内使用这些,所以它是本地的,模糊的名称不会遍及整个代码。 Here is a live example.
这是一个实例。
First, you repeat stuff: 首先,你重复一下:
The name kSensorActive
doesn't have to say Sensor
if you already specified that it's a SensorStatus
in the name. 该名
kSensorActive
不必说, Sensor
,如果你已经指定,这是一个SensorStatus
之名。 Or you could remove Sensor
from SensorStatus
if it's inside MySensor
. 或者你可以删除
Sensor
从SensorStatus
如果它里面MySensor
。 Maybe both. 也许两者。
The idea behind wrapping things inside classes and namespaces is that you CAN use the same name over and over again, for something that is "the same sort of thing", rather than having completely unique names throughout. 在类和命名空间中包装内容的想法是,你可以一遍又一遍地使用相同的名称,对于“同类的东西”,而不是在整个过程中使用完全唯一的名称。
You can also, locally, change the names with using
, something like this 您也可以在本地
using
类似的方式更改名称
using Status = Sensors::MySensor::SensorStatus;
and then us Status::kSensorActive
where you previously used the long thing. 然后我们
Status::kSensorActive
你以前使用过的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.