首页 > 解决方案 > 使用静态 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) 具有以下优势:

使用此模式时要记住哪些缺点、陷阱或其他事项?

标签: c++c++11

解决方案


(A) 通过从最终可执行文件中删除不必要的变量可能更难优化。

如果要对常量进行分组,请考虑namespace为此目的使用 a 。

namespace ConstantGroup
{
    constexpr int a = 1;

    // Here best solution might depend on usage and c++ version
    const std::string b;    
}

将常量作为一个组传递确实没有多大意义。如果某些东西确实是恒定的,那么您需要一个单一的定义并始终使用它。

此外,如果常量非常特定于一个类,则使其成为该类的(静态)成员。


推荐阅读