源文件全局范围内的 constexpr 变量
constexpr variable in source file global scope
在源文件中声明 constexpr 常量的正确方法是什么?我分为两种方式:
constexpr int ORDER = 1;
对
namespace {
constexpr int ORDER = 1;
} // unnamed namespace
我质疑包装到未命名命名空间的有用性的原因是因为在全局范围内,constexpr
意味着 static
。与头文件中的编写方式非常相似
static constexpr int ORDER = 1;
使 static
只是一个重复,我假设源文件也应该同样适用,因此内部链接应该保证“constexpr
在源文件的全局变量中声明的变量范围”。
是这样吗?有不同的建议吗?
不需要将在源文件中声明的 constexpr
变量包含在未命名的命名空间中。由于最终目标是实现内部链接,因此您必须记住 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
- it is explicitly declared extern, or
- 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.
即自"constexpr
implies const
and const
on namespace scope implies internal linkage"以来,再说
就多余了
static constexpr int ORDER = 1;
甚至
namespace {
static constexpr int ORDER = 1;
}
如果您想要内部联系的切实证据 属性,请考虑
在源文件中声明 constexpr 常量的正确方法是什么?我分为两种方式:
constexpr int ORDER = 1;
对
namespace {
constexpr int ORDER = 1;
} // unnamed namespace
我质疑包装到未命名命名空间的有用性的原因是因为在全局范围内,constexpr
意味着 static
。与头文件中的编写方式非常相似
static constexpr int ORDER = 1;
使 static
只是一个重复,我假设源文件也应该同样适用,因此内部链接应该保证“constexpr
在源文件的全局变量中声明的变量范围”。
是这样吗?有不同的建议吗?
不需要将在源文件中声明的 constexpr
变量包含在未命名的命名空间中。由于最终目标是实现内部链接,因此您必须记住 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
- it is explicitly declared extern, or
- 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.
即自"constexpr
implies const
and const
on namespace scope implies internal linkage"以来,再说
static constexpr int ORDER = 1;
甚至
namespace {
static constexpr int ORDER = 1;
}
如果您想要内部联系的切实证据 属性,请考虑