在哪里定义编译时常量?

Where to define compile-time constants?

我做了一个超级简单的设计来解决一个问题。

现在,这乍一看似乎非常微不足道,但由于有很多方法可以做到这一点,由于我缺乏专业经验,这让我很困惑。

我应该在哪里定义那些编译时常量? (总是假设我使用的是当前最高的 C++ 标准版本)

在命名空间中? class里面?在class外的一个.h里?在 class 之外的 .cpp 中?只是将它们用作神奇数字并添加一些评论?静态的?非静态?常数?构造函数?模板甲板尺寸以防它更大?

我想到的:

class JolloManager
{
private:
    constexpr static int rounds = 3;
    constexpr static int deckSize = 52;
    constexpr static int princeId = 1;
    constexpr static int princessId = 2;
    std::array<int, deckSize> deck;
public:
    JolloManager() {};
};

这是正确的吗?

在 C++17 中,定义 compile-time 整数常量很容易。

首先,您应该决定常量是否应该限定在 class 范围内。如果将其作为 class 成员有意义( 例如, 它属于 class 代表的概念),那么将其设为 class 成员。否则不要。

作为 class 成员,写:

class JolloManager {
    constexpr static int rounds = 3;
};

就是这样。在 C++17 中不再需要 out-of-line 定义。

如果它不会成为 class 成员,但您希望包含您的 header 的每个人都能够访问该值,那么请在 header 中写入:

inline constexpr int rounds = 3;

(从技术上讲,使用 inline 的原因是为了避免当多个翻译单元中的内联函数 ODR-used 变量时 ODR 违规。)

如果该值是只有一个 .cpp 文件需要访问的实现细节,则在该 .cpp 文件中写入以下内容以为其提供内部链接(即, 防止与其他翻译单元中的名称冲突):

constexpr int rounds = 3;  // no `inline` this time

最后,如果只有一个函数需要常量,您可以将其设为该函数的局部值:

void foo() {
    constexpr int rounds = 3;
}