如何在交换机的情况下使用右值引用

I want to use t(rvalue reference) in a case of switch(T), but I get an error the value of 't' is not usable in a constant expression. How to do it the right way.

#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;
    }
}
评论
  • 思雁
    思雁 回复

    You can't use an rvalue reference as a case label, since it is not a constant expression. You can however use a const int variable:

    int const t = 5;
    switch(...)
    {
      case t : ...  // ok
    }
    

    这可能应该是:

    constexpr int t = 5;
    

    也一样

    请注意,尝试执行以下操作:

    int const &&t = 5;
    

    will not work either, since the initializer is not a constant expression, so there is no way that I'm aware of that lets you use an rvalue reference as a case label.