我正在用 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};
我最初的计划是使用这个结构定义所有操作码,因为我的印象是const
首选使用#define
对于 C++ 常量。此外,我将能够清晰地对操作码的所有相关属性进行分组。
然而,这似乎不适用于 switch 语句,正如我最初的意图。以下代码将无法编译,并且 Visual Studio 会给出错误“case 表达式不是常量”。
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;
}
我还下载了最新的 Visual Studio 编译器(MSVC 2013 年 11 月 CTP)来尝试利用constexpr
来自 C++11,但我遇到了同样的问题,并且无法编译。在这里,我将结构转换为类并尝试利用constexpr
,以确保成员instruction
可以用作编译时常量。
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);
我不太确定此时该怎么做,因为编译器似乎不明白结构值被分配为常量。
那么有什么方法可以在 switch 语句中使用结构成员,或者我应该切换到使用#define
?或者,是否有更好的方法来做到这一点,同时仍然保留一些组织?我非常感谢您提供的任何帮助或见解,谢谢!
EDIT:抱歉,我应该更清楚地表明 next_instruction 只是一个 int,而不是一个instruction
结构/对象