RaG*_*__M 3 c++ constexpr c++11 c++14
我有以下代码
constexpr int into(int a,int b)
{
int c=a*b;
return c;
}
int main()
{
constexpr int &n=into(5,5);
}
Run Code Online (Sandbox Code Playgroud)
我已阅读(在MSDN中)
该关键字
constexpr
是在C++ 11中引入的,并在C++ 14中进行了改进.这意味着不断表达.例如const
,它可以应用于变量,以便在任何代码尝试修改该值时引发编译器错误.
在我阅读之后,我认为constexpr
可以代替使用const
,但对于上面的代码我得到一个编译器错误说明
Run Code Online (Sandbox Code Playgroud)`int main()': invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'`
什么时候constexpr
更换const
,它工作正常.我不明白这种行为; 有人可以解释一下吗?
不像const
,它适用于int
,所述constexpr
关键字直接施加到常量引用类型的变量int&
,其具有没有影响.
typedef int &int_ref;
int main() {
int x = 1;
int &a = x; // OK
int_ref b = x; // OK, int_ref is 'int &'
const int &c = 1; // OK, reference to const int
const int_ref d = 1; // error: type of d is 'int &'
// qualifier on reference are being ignored
}
Run Code Online (Sandbox Code Playgroud)
constexpr int &n
并且constexpr int_ref n
是相同的,const int &n
而且const int_ref n
有限定词不同.
归档时间: |
|
查看次数: |
552 次 |
最近记录: |