我正在用C++编写一个微处理器模拟器,我的目标之一是使代码非常易读.为了实现操作码,我有一个结构,我用它来表示单独的处理器指令,它包含操作码和程序计数器的推进程度.我们的想法是将有关每条指令的相关信息分组.
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};
Run Code Online (Sandbox Code Playgroud)
我最初的计划是使用这个结构来定义所有的操作码,因为我认为const它更适合#define用于C++常量.此外,我将能够干净地分组操作码的所有相关属性.
但是,似乎这对于switch语句不起作用,正如我最初的意图.以下代码将无法编译,Visual Studio将提供错误"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;
}
Run Code Online (Sandbox Code Playgroud)
我还下载了最新的Visual Studio编译器(MSVC 2013年11月CTP)以尝试利用constexprC++ 11,但我遇到了同样的问题,并且它无法编译.在这里,我将我的结构转换为一个类并尝试利用constexpr …