在 C++ 中在哪里定义 class 常量?

Where to define class constants in C++?

在 C++ 中,为了让代码更整洁,我想在我的头文件中声明一组值作为常量,例如:

constexpr float SIZE_SMALL = 1.5f; 
constexpr float SIZE_MEDIUM = 2.5f; 
constexpr std::string COLOR_RED = "RED"; 
constexpr std::string MATERIAL_SILK = "SILK";
...etc

但这变得太长太笨拙了。此外,一些常量可以组合在一起,因为它们描述了相同 属性 的不同值,例如SIZE_SMALLSIZE_MEDIUM.

在我的头文件中写这个的最好方法是什么?我想到了结构,例如

struct SIZE
{
float SMALL; 
float MEDIUM; 
}

但是我必须在我的 .cpp 中声明和定义一个变量,这有点违背了所有这些的目的。

then I have to declare and define a variable in my .cpp and that kinda beats the purpose of all this.

不,你不知道。您可以使字段 staticconstexpr :

struct SIZES {
    static constexpr const float SMALL = 1.5f;
};

但是,我建议不要这样做。您不仅不必创建此 class 的实例,而且您也不应该创建此 class 的实例(为什么?)。那么为什么首先使用 class 呢?使用 namespaces 代替常量分组:

namespace SIZES {
    constexpr float SMALL = 1.5f; 
}

I have some 50+ of these constants in the same name space

除非你找到一种方法让编译器读懂你的想法,否则你必须将它们全部写下来。严重的是,唯一可以简化的方法是这些常量之间是否存在某种关系,例如 SMALL + 1.0f = MEDIUM,但这在您的问题中并不明显。

这取决于您的实际使用,但consider using proper strong types而不是基本类型。例如,要声明大小,请将它们设为 size 类型,而不是 float。这不会直接解决您的分组问题,但它可以为您提供强类型的所有其他好处,并且还可能有助于分组:

struct size {
private: float value;
public:
    explicit constexpr size(float value) : value{value} {}
    explicit constexpr operator float() const noexcept { return value; }
};

namespace default_sizes {
    constexpr auto SMALL = size{1.5f};
    constexpr auto MEDIUM = size{2.5f};
    // …
}

事实上,对于特定领域的使用,除了非常有限的情况外,我 通常 避免裸露的基本类型,并始终将它们封装在它们自己的特定领域类型中。