[英]constexpr versus anonymous namespace
创建const值时,以下两种模式有什么区别?
constexpr int some_val = 0;
VS
namespace {
const int some_val = 0;
}
我已经习惯了第二种方法,但是第一种等效吗?
未命名的命名空间充当变量的static
:链接。
namespace {
const int some_val = 0;
}
等效于:
static const int some_val = 0;
constexpr
不会改变这一点: 演示
现在我们可以比较const
与constexpr
:
constexpr
变量是在编译时已知的不可变值(因此可以在常量表达式中使用) const
变量是不可变的值,可以在运行时进行初始化。 所以你可能有
int get_int() {
int res = 0;
std::cin >> res;
return res;
}
const int value = get_int();
但不是
constexpr int value = get_int(); // Invalid, `get_int` is not and cannot be constexpr
最后,某些const
值将被视为constexpr
因为它将用于:
const int some_val = 0; // equivalent to constexpr int some_val = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.