【问题标题】:Using class types in switch在 switch 中使用类类型
【发布时间】:2011-12-10 10:53:24
【问题描述】:

我正在尝试switch 自定义类型。标准说

条件应为整型、枚举型或 单个非显式转换函数到的类类型 存在整数或枚举类型 (12.3)。如果条件是 类类型,通过调用该转换来转换条件 函数,并使用转换的结果代替 本节其余部分的原始状态。不可缺少的 进行促销活动。

这表明具有到enum 类型的隐式转换函数的类型应该是有效的switch 表达式。但是当我尝试使用这个措辞时,Visual Studio 给出了一个关于 switch 表达式是非整数的错误。 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&lt;Token&gt;::iterator

编辑:

请阅读问题。你想看我的代码吗? 我在上面一行中所说的非常明显怎么样?也许我应该用粗体和斜体写成五十个字母。

std::vector<Token>::iterator begin = vector.begin();
switch(*begin) {
case TokenType::stuff:
}

【问题讨论】:

  • 哦,有趣...你能发布一些伪代码吗?
  • @AhmedMasud 很清楚......您只需使用可以转换为整数类型的对象。
  • 它在 GCC 上为我工作。贴一些代码?
  • 你为什么要发布很多不相关的代码而没有相关代码?像ideone.com/6K2FC 这样的东西可以用VC++ 2005 编译好(没有更新的)。 - WTF 是否支持这样一个糟糕的问题?!​​
  • 类似代码compiles fine in g++.

标签: c++ visual-studio-2010 c++11


【解决方案1】:

看起来像 VC 中的一个错误。 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 感到高兴?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2020-06-01
    • 2022-08-17
    • 2018-10-17
    • 2021-09-29
    相关资源
    最近更新 更多