先看一个简单的例子:
class test{
public:
constexpr test(){
}
constexpr int operator + (const test& rhs){
return 1;
}
};
int main() {
test t;
constexpr int b = t + test(); // 可以编译通过
int w = 10; //
constexpr int c = w + 2; // 编译不通过, w不是constexpr
return 0;
}
如果改成:
class test{
public:
constexpr test(){
a= 12;
}
constexpr int operator + (const test& rhs){
return 1 + a;
}
int a;
};
int main() {
test t;
constexpr int b = t + test(); //编译不通过, b不是constexpr
int w = 10;
constexpr int c = w + 2; // 编译不通过, c不是constexpr
return 0;
}
这里的test 构造函数声明成 constexpr 但是 t的变量并不是constexpr , 主要是
+ test()
能够变成 constexpr.
constexpr int b = t + test();
展开就是
constexpr int b = t.operator+( test() );
#include <iostream>
struct test {
int val;
constexpr test(int val) : val(val) { }
};
template<int N>
struct CC {
double m[N];
};
int main()
{
constexpr int c =12;
constexpr auto w = test(c);
// w.val = 12 // 编译报错, w 是read -only, 不可以被修改
CC<w.val> k; // usage where compile time constant is required
std::cout << std::end(k.m) - std::begin(k.m) << std::endl;
return 0;
}
但是constexpr constructors 也不是这个类所有的实例都不可以被修改,类内的对象还是可以修改的。
#include <iostream>
struct test {
int val;
constexpr test(int val) : val(val) { }
};
int main()
{
test a(1);
++a.val;
std::cout << a.val << std::endl;
return 0;
}