c++ - 使用静态 const 结构对相关的类常量进行分组 (C++11)
问题描述
使用以下(A)有什么(缺点)优点:
// .h
class SomeClass
{
static const struct ConstantGroup
{
int a = 1;
string b = "b";
// ... etc.
} CONSTANT;
};
// .cpp
const SomeClass::ConstantGroup SomeClass::CONSTANT;
与(B):
// .h
class SomeClass
{
static const int A;
static const string B;
// .. etc.
};
// .cpp
const int SomeClass::A = 1;
const string SomeClass::B = "b";
...对于一些相关的静态类常量组?假设不涉及模板并且常量包含简单类型(POD 或字符串)。
到目前为止,我认为 (A) 具有以下优势:
相关常量可以作为一个组传递编辑:正如评论中所指出的,这通常是不希望的。- 鉴于常量经常一起访问,我们可以在需要时为结构创建简写以提高可读性,即:
static const auto & SHORTHAND = SomeClass::LONG_NAME_FOR_CONSTANTS;
使用此模式时要记住哪些缺点、陷阱或其他事项?
解决方案
(A) 通过从最终可执行文件中删除不必要的变量可能更难优化。
如果要对常量进行分组,请考虑namespace
为此目的使用 a 。
namespace ConstantGroup
{
constexpr int a = 1;
// Here best solution might depend on usage and c++ version
const std::string b;
}
将常量作为一个组传递确实没有多大意义。如果某些东西确实是恒定的,那么您需要一个单一的定义并始终使用它。
此外,如果常量非常特定于一个类,则使其成为该类的(静态)成员。
推荐阅读
- adobe - 在 Adobe After Effects CC 2018 上设置冻结图片时,运动跟踪器失败
- javascript - 反应 setState 不改变特定属性的状态
- ember.js - Ember:如何将 UnwatchedDir 与树合并/取消监视子目录?
- typescript - Angular 6 数组得到更新,没有进行任何更新
- python - 熊猫年日列到月列
- python - pipenv:即使我安装了一个包,为什么在自动创建锁定文件时运行 pipenv lock
- java - 如何选择在 selenium-java 运行时生成 div[i] 的复选框?
- java - Instance#get() 是否为 CDI 中的 @ApplicationScoped bean 返回相同的实例?
- android - 我正在尝试使用 C# 将图像从我的 android 应用程序保存到 microsoft sql server
- python-3.x - TypeError:无法腌制 CompiledFFI 对象