在 constexpr 中使用的非常量:标准怎么说
Non-const used in a constexpr : what does the standard say?
C++11 iso 标准对这样的表达式有什么看法:
class MyClass
{
public:
constexpr int test()
{
return _x;
}
protected:
int _x;
};
_x
constexpr
中使用非常量:它会产生错误,还是简单地忽略constexpr
(就像我们传递非常量参数时一样)?
这很好,虽然有些没用:
constexpr int n = MyClass().test();
由于MyClass
是一个聚合,因此像这样对其进行值初始化将对所有成员进行值初始化,因此这只是零。但是通过一些润色,这可以变得真正有用:
class MyClass
{
public:
constexpr MyClass() : _x(5) { }
constexpr int test() { return _x; }
// ...
};
constexpr int n = MyClass().test(); // 5
如果表达式未解析为常量表达式,则不能将其用作常量表达式。但它仍然可以使用:
#include <array>
constexpr int add(int a, int b)
{
return a+b;
}
int main()
{
std::array<int, add(5,6)> a1; // OK
int i=1,
int j=10;
int k = add(i,j); // OK
std::array<int, add(i,j)> a2; // Error!
}
相关文章:
- C4204:使用的非标准扩展:非常量聚合初始值设定项
- 从常量字符*、字符*参数到标准::字符串的直接转换接口
- 常量转发引用给出错误 C2440:"正在初始化":无法从"常量标准::字符串"转换为"常量标准::字符串 &&"
- 从另一个常量标准::映射初始化一个常量标准::映射的一部分
- 有没有办法为静态对象成员定义一个符合开关标准的常量?
- 兼容的声明 __attribute__ ((节( ".abc.dfe" ))) 常量易失性 uint8 属性变量 = 0;- 符合MISRA标准
- C++17 标准 - 抛弃静态常量
- 在符合 ODR 标准的头文件中使用常量
- C++标准是否保证函数返回值具有常量地址?
- 静态常量标准::矢量
- 用于定义公共变量静态常量整数的C++标准
- 在 constexpr 中使用的非常量:标准怎么说
- C++11标准中的核心常量表达式是什么
- C++11:常量和引用类型上“auto”操作的标准引用
- 带有标准容器和常量引用的c++代码显示出意外的内存
- 如何将常量标准::矢量<无符号字符>转换为字符
- 标准::矢量元素中的常量引用
- C++错误 C2040:"e":"记录器"的间接级别与"常量标准::异常 &"不同
- 标准库/模板化容器的常量语义的经验法则
- 奇怪的标准::带有常量字符*的cout行为