jeudi 31 mars 2016

remove repetition when switching enum class

When I switch on an enum class I have to restate the enum class in every case. This bugs me since outside of constexpr-constructs it is hard to imagine what else I could mean. Is there away to inform the compiler that everything inside a block should be resolved to an enum class of my choice if there is a match?

consider the following example that contains a compiling snippet and for comparisson a non compiling snippet (commented out) that I would like to write.

#include <iostream>

enum class State : std::uint8_t;
void writeline(const char * msg);
void Compiles(State some);

enum class State : std::uint8_t
{
    zero = 0,
    one = 1
};

int main()
{
    Compiles(State::zero);
    return 0;
}

void Compiles(State some)
{
    switch (some)
    {
    case State::zero: //State::
        writeline("0");
        break;
    case State::one: //State::
        writeline("1");
        break;
    default:
        writeline("d");
        break;
    }
}


//void WhatIWant(State some)
//{
//  using State{ //this makes no sense to the compiler but it expresses what I want to write
//      switch (some)
//      {
//      case zero: //I want the compiler to figure out State::zero
//          writeline("0");
//          break;
//      case one: //I want the compiler to figure out State::one
//          writeline("1");
//          break;
//      default:
//          writeline("d");
//          break;
//      }
//  }
//}

void writeline(const char * msg)
{
    std::cout << msg << std::endl;
}

Is there a way to use a switch statement and have the compiler figure out the enum class, maybe after giving a hint once?

Aucun commentaire:

Enregistrer un commentaire