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.
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};
My original plan was to define all the opcodes using this struct, as I was under the impression that const
was preferred to using #define
for C++ constants. In addition, I would be able to cleanly group all related attributes of an opcode.
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".
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 << "Unrecognized opcode" << std::endl;
break;
}
I've also downloaded the latest Visual Studio compiler (MSVC November 2013 CTP) to try to leverage constexpr
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 constexpr
, to ensure that the members of an instruction
could be used as compile-time constants.
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);
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.
So is there any way to use a struct member in a switch statement, or should I just switch to using #define
? 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!
EDIT: Sorry, I should have made it clearer that next_instruction is just an int, not an instruction
struct/object