title: C++: struct member in a switch statement
body: <p>I am writing a microprocessor emulator in C++, and one of my goals was to make it the code very readable.  To implement opcodes, I have a struct which I am using to represent individual processor instructions, and it contains both the opcode and how far to advance the program counter.  The idea was to group related information about each instruction.</p>
  
  <pre><code>struct instruction
  {
      const int opcode; // instruction opcode
      const int op_size; // how far to advance Program Counter
  };
  
  const instruction HALT{0x76, 1};
  const instruction NOP {0x00, 1};
  </code></pre>
  
  <p>My original plan was to define all the opcodes using this struct, as I was under the impression that <code>const</code> was preferred to using <code>#define</code> for C++ constants.  In addition, I would be able to cleanly group all related attributes of an opcode.</p>
  
  <p>However, it seems that this will not work for switch statements, as I originally intended.  The following code will not compile, and Visual Studio gives the error "case expression not constant".</p>
  
  <pre><code>switch (next_instruction) { // next_instruction is an int parsed from a file
      case HALT.opcode:
          // do stuff
          break;
      case NOP.opcode:
          // do stuff
          break;
      default:
          std::cout &lt;&lt; "Unrecognized opcode" &lt;&lt; std::endl;
              break;
      }
  </code></pre>
  
  <p>I've also downloaded the latest Visual Studio compiler (MSVC November 2013 CTP) to try to leverage <code>constexpr</code> from C++11, but I had the same problem, and it will not compile.  Here I converted my struct to a class and attempted to leverage <code>constexpr</code>, to ensure that the members of an <code>instruction</code> could be used as compile-time constants.</p>
  
  <pre><code>class Instruction
  {
    public:
      constexpr Instruction(int code, int size) : opcode(code), op_size(size) {}
      const int opcode; // instruction opcode
      const int op_size; // how far to advance Program Counter
  };
  
  constexpr Instruction HALT(0x76, 1);
  constexpr Instruction NOP (0x00, 1);
  </code></pre>
  
  <p>I'm not really sure what to do at this point, since it appears that the compiler does not understand that the struct values are assigned as constants.</p>
  
  <p>So is there any way to use a struct member in a switch statement, or should I just switch to using <code>#define</code>?  Alternatively, is there a better way to do this while still retaining some organization?  I'd really appreciate any help or insight you can offer, thanks!</p>
  
  <p><strong>EDIT:</strong> Sorry, I should have made it clearer that next_instruction is just an int, not an <code>instruction</code> struct/object</p>