consteval可用在立即函数(immediate function),立即函数实际上是编译时运行的函数,也就是它的参数在编译时是“确定的”(常量),它的结果也是常量。constexpr可用于编译或运行时函数,它的结果是常量。它们区别如下例,特别注意的是注释掉的那行。
using namespace std;
consteval int compileconst(int n) { return n+1;}
constexpr int runcompileconst(int n) { return n+1;}
int main()
{
int nn= compileconst (100);
cout <<nn<<endl;
// int nnn= compileconst (nn); //error , nn is not const
int nnn= runcompileconst (nn);
cout<<nnn;
return 0;
}
constinit variable表示该变量在程序(线程)开始就被分配的,与程序(线程)具有相同的生命周期,因此它有点static的意思,在编译时被初始化。下面例子中被注释掉的两行会产生编译错误,从中可以看出,constexpr的变量是const类型,只读,constinit是说变量在程序开始时被初始化,是static类型,不能在运行时被创建,变量不要求是const类型。
using namespace std;
consteval int sqr(int n) { return n * n;}
constexpr int res1 = sqr(5);
constinit int res2 = sqr(5);
int main() {
cout << res1 <<endl;
// cout<<++res1<<endl; // error: increment of read-only variable 'res1'
cout << res2 <<endl;
cout<<++res2<<endl;
//constinit auto res3 = sqr(5); // error: 'constinit' can only be applied to a variable with static or thread storage duration
constinit thread_local auto res3 = sqr(5);
cout << res3 <<endl;
}