繁体   English   中英

在哪里定义编译时常量?

[英]Where to define compile-time constants?

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

在此处输入图像描述

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

我将在哪里定义这些编译时间常量? (一直假设我用的是电流最高的C++标准版)

在命名空间中? class 内部? class在外啊? 在class之外的.cpp? 只是将它们用作幻数并添加一些评论? static? 非静态的? 常量? 常量表达式? 模板甲板尺寸以防它更大?

我想到的:

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 中,定义编译时 integer 常量很容易。

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

作为 class 成员,请写:

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

而已。 C++17 不再需要外线定义。

如果它不是 class 成员,但您希望包括您的 header 的每个人都能够访问该值,则将其写入 header:

inline constexpr int rounds = 3;

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

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

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

最后,如果仅单个 function 需要该常量,则可以将其设置为该 function 的本地:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM