Search code examples
c++switch-statementrvalue-reference

how to use a rvalue reference in a switch's case


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;
    }
}

Solution

  • Note that case labels in a switch statement need to be constant expressions.

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

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

    Note that trying to do something like:

    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.

    Note also, that something like:

    int const t = ...
    

    will not work unless the initializer is a constant expression (i.e. known at compile time). So:

    int const t = 5;
    

    will work, but:

    int n = 5;
    int const t = n;
    

    will not.