小编dco*_*ill的帖子

C++:switch语句中的struct成员

我正在用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 …

c++ struct visual-c++ constexpr c++11

8
推荐指数
2
解决办法
3581
查看次数

标签 统计

c++ ×1

c++11 ×1

constexpr ×1

struct ×1

visual-c++ ×1