使用switch中的类类型

Using class types in switch

本文关键字:类型 switch 使用      更新时间:2023-10-16

我试图在自定义类型上switch

条件必须是整型、枚举型或a为其提供单个非显式转换函数的类类型存在整型或枚举类型(12.3)。如果条件是类类型时,通过调用该转换来转换条件函数,并使用转换的结果代替本节其余部分的原始条件。积分执行提升。

这表明一个类型如果有一个隐式转换函数到enum类型,那么它应该是一个有效的switch表达式。但是当我尝试使用这种措辞时,Visual Studio给出了一个关于开关表达式是非积分的错误。VS只是在这方面不兼容吗?

类类型的定义是
    struct Token {
        Token()
            : line(0)
            , columnbegin(0)
            , columnend(0) {}
        Token(const Codepoint& cp) {
            *this = cp;
        }
        template<typename Iterator> Token(Iterator begin, Iterator end) {
            columnend = 0;
            columnbegin = 0;
            line = 0;
            while(begin != end) {
                *this += *begin;
                begin++;
            }
        }
        operator TokenType() {
            return type;
        }
        Token& operator+=(const Codepoint& cp) {
            if (cp.column >= columnend)
                columnend = cp.column;
            if (columnbegin == 0)
                columnbegin = cp.column;
            Codepoints += cp.character;
            if (line == 0)
                line = cp.line;
            return *this;
        }
        Token& operator=(const Codepoint& cp) {
            line = cp.line;
            columnbegin = cp.column;
            columnend = cp.column;
            Codepoints = cp.character;
            return *this;
        }
        int line;
        int columnbegin;
        int columnend;
        TokenType type;
        string Codepoints;
    };

switch(*begin)为错误线,其中beginvector<Token>::iterator

编辑:

请读问题。你想看我的代码吗?那么我在上面那行所陈述的非常明显的呢?也许我应该把它改成50个字母的粗体和斜体。
std::vector<Token>::iterator begin = vector.begin();
switch(*begin) {
case TokenType::stuff:
}

看起来像VC中的一个bug。GCC 4.5和4.7编译这个,没有问题:

enum class e { roy, gee, biv };
struct s { operator e() { return e::gee; } };
void f() {
    switch ( s() ) {
        case e::roy: case e::biv: case e::gee: break;
    }
}

这个更小的测试用例让VC高兴吗?