constexpr 的按位运算是否会导致 constexpr?
Do bitwise operations of constexpr result in constexpr?
我用下面显示的方式定义了一些常量
constexpr int a = 1;
constexpr int b = 2;
我的问题是所有只使用a
和b
的算术和按位运算是否会被编译器视为constexpr
?
例如,我想知道编译器是否保证在 c
编译时计算表达式?如果没有,有没有办法求编译时间计算?
c = (a + b) & (a | b);
My question is whether all arithmetic and bitwise operations that only use a
and b
will be considered as constexpr
by the compiler?
这样的表达式在 constexpr
上下文中可用,但有一些例外(必须避免任何导致未定义或实现定义的行为的行为,例如负数的按位右移、除以零、溢出有符号类型)。
For example, I'm wondering whether compiler is guaranteed to calculate the expression for c compile time?
仅当在需要编译时上下文的上下文中使用表达式时。
If not, is there a way to ask for compile time calculations?
这就是应用于变量的 constexpr
关键字的作用。假设您不能只将限定符添加到 c
本身,因为它被用作变量(例如,稍后根据运行时数据重新分配)您仍然可以强制计算为 constexpr
:
constexpr auto cvalue = (a + b) & (a | b);
c = cvalue;
我用下面显示的方式定义了一些常量
constexpr int a = 1;
constexpr int b = 2;
我的问题是所有只使用a
和b
的算术和按位运算是否会被编译器视为constexpr
?
例如,我想知道编译器是否保证在 c
编译时计算表达式?如果没有,有没有办法求编译时间计算?
c = (a + b) & (a | b);
My question is whether all arithmetic and bitwise operations that only use
a
andb
will be considered asconstexpr
by the compiler?
这样的表达式在 constexpr
上下文中可用,但有一些例外(必须避免任何导致未定义或实现定义的行为的行为,例如负数的按位右移、除以零、溢出有符号类型)。
For example, I'm wondering whether compiler is guaranteed to calculate the expression for c compile time?
仅当在需要编译时上下文的上下文中使用表达式时。
If not, is there a way to ask for compile time calculations?
这就是应用于变量的 constexpr
关键字的作用。假设您不能只将限定符添加到 c
本身,因为它被用作变量(例如,稍后根据运行时数据重新分配)您仍然可以强制计算为 constexpr
:
constexpr auto cvalue = (a + b) & (a | b);
c = cvalue;