简体   繁体   English

源文件全局范围内的 constexpr 变量

[英]constexpr variable in source file global scope

What is the proper way to declare a constexpr constant in a source file?在源文件中声明 constexpr 常量的正确方法是什么? I'm split between two ways:我分为两种方式:

constexpr int ORDER = 1;

vs对比

namespace {
constexpr int ORDER = 1;
} // unnamed namespace

The reason I question the usefulness of wrapping into an unnamed namespace is because at global scope, constexpr implies static .我质疑包装到未命名命名空间的有用性的原因是因为在全局范围内, constexpr意味着static So similar to how in header files writing如此类似于头文件中的写入方式

static constexpr int ORDER = 1;

makes static just a repetition, I'm assuming that the same should apply in source files as well, hence internal linkage should be guaranteed for " constexpr variables declared in a source file's global scope".使static只是一个重复,我假设同样应该适用于源文件,因此应该保证“在源文件的全局范围内声明的constexpr变量”的内部链接。

Is this the case?是这种情况吗? Are there different suggestions?有不同的建议吗?

It's not required to enclose constexpr variables, declared in a source file, in an unnamed namespace.不需要将在源文件中声明的constexpr变量包含在未命名的命名空间中。 Since the end goal is to achieve internal linkage you have to remember this :由于最终目标是实现内部链接,因此您必须记住这一点

The name of an entity that belongs to a namespace scope has internal linkage if it is the name of属于命名空间范围的实体的名称具有内部链接,如果它是

  • a variable, variable template,一个变量,变量模板,
  • function, or function template that is explicitly declared static;显式声明为静态的函数或函数模板; or或者
  • a non-template variable of non-volatile const-qualified type , unless非 volatile常量限定类型的非模板变量,除非
    • it is explicitly declared extern, or它被明确声明为 extern,或
    • it is inline or exported, or它是内联的或导出的,或者
    • it was previously declared and the prior declaration did not have internal linkage;先前已申报且先前申报无内部联系; or或者
  • a data member of an anonymous union.匿名联合的数据成员。

ie since " constexpr implies const and const on namespace scope implies internal linkage" , it's superfluous to say即因为constexpr隐含const并且const在命名空间范围内隐含内部链接” ,所以说是多余的

static constexpr int ORDER = 1;

or even甚至

namespace {
  static constexpr int ORDER = 1;
}

If you want a tangible proof of the internal linkage property, consider this compilation error如果您想要内部链接属性的有形证明,请考虑此编译错误

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

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