简体   繁体   English

在哪里定义编译时常量?

[英]Where to define compile-time constants?

I made a super simple design to start solving a problem.我做了一个超级简单的设计来开始解决问题。

在此处输入图像描述

Now, this might seem like super trivial at first, but since there are tons of ways to do this, it confuses me, due to my lack of professional experience.现在,起初这可能看起来非常微不足道,但由于有很多方法可以做到这一点,由于我缺乏专业经验,这让我感到困惑。

Where would I define those compile time constants?我将在哪里定义这些编译时间常量? (Always suppose I'm using the highest current C++ standard version) (一直假设我用的是电流最高的C++标准版)

In a namespace?在命名空间中? Inside the class? class 内部? In ah outside the class? class在外啊? In the.cpp outside the class?在class之外的.cpp? Just use them as magic numbers and add some comment?只是将它们用作幻数并添加一些评论? static? static? non-static?非静态的? const?常量? constexpr?常量表达式? template the deck size in case its bigger?模板甲板尺寸以防它更大?

What I thought of:我想到的:

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() {};
};

Is this correct?这个对吗?

In C++17, defining compile-time integer constants is easy.在 C++17 中,定义编译时 integer 常量很容易。

First, you should decide whether or not the constant should be scoped to a class.首先,您应该确定常量是否应限定为 class。 If it makes sense to have it as a class member ( eg, it pertains to the concept that the class represents) then make it a class member.如果将其作为 class 成员有意义(例如,它属于 class 所代表的概念),则将其设为 class 成员。 Otherwise, don't.否则,不要。

As a class member, write:作为 class 成员,请写:

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

That's it.而已。 No out-of-line definition is required anymore in C++17. C++17 不再需要外线定义。

If it's not going to be a class member, but you want everyone who includes your header to be able to access the value, then write this in the header:如果它不是 class 成员,但您希望包括您的 header 的每个人都能够访问该值,则将其写入 header:

inline constexpr int rounds = 3;

(Technically, the reason to use inline is to avoid ODR violations when the variable is ODR-used by an inline function in multiple translation units.) (从技术上讲,使用inline的原因是当变量被多个翻译单元中的内联 function 使用 ODR 时避免 ODR 违规。)

If the value is an implementation detail that only one .cpp file needs access to, then write the following in that .cpp file to give it internal linkage ( ie, prevent clashing with names in other translation units):如果该值是只有一个.cpp文件需要访问的实现细节,则在该.cpp文件中写入以下内容以提供内部链接(即,防止与其他翻译单元中的名称冲突):

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

Finally, if the constant is only needed by a single function, you can make it local to that function:最后,如果仅单个 function 需要该常量,则可以将其设置为该 function 的本地:

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

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

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