我想在switch(T)的情况下使用t(rvalue reference),但我得到一个错误信息 the value of 't' is not usable in a constant expression
. 如何做才是正确的。
#include <iostream>
using namespace std;
int main(){
int (&&t)=5;
int T{};
switch(T){
case t: // error in this case
cout<<t<<endl;
break;
default:
cout<<"default"<<endl;
break;
}
}
注意 盒标 在...中 switch
语句需要是常量表达式。
你不能使用rvalue引用作为case标签,因为它不是一个常量表达式。但是你可以使用一个编译时初始化的变量。
constexpr int t = 5;
switch(...)
{
case t : ... // ok
}
请注意,试图使用类似:
int const &&t = 5;
也是行不通的,因为初始化器不是一个常量表达式,所以我不知道有什么方法可以让你使用rvalue引用作为案例标签。
还请注意,除非初始化器是常量表达式,否则类似:
int const t = ...
除非初始化器是一个常量表达式(即在编译时已知),否则将无法使用。所以。
int const t = 5;
可以用,但是:
int n = 5;
int const t = n;
则不行。