“枚举类”仿真或固体替代MSVC 10.0 [英] "enum class" emulation or solid alternative for MSVC 10.0

查看:112
本文介绍了“枚举类”仿真或固体替代MSVC 10.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个hacky类型的解决方案以下问题:
GCC 4.4+接受以下c ++ 0x代码:

I'm looking for a hacky kind of solution to the following problem: GCC 4.4+ accepts the following c++0x code:

enum class my_enum
{
    value1,
    value2
};

这样允许使用:

my_enum e = my_enum::value1;

所有的铃声和​​口哨。我想让这个代码与MSVC 2010兼容,这样的效果是使用的语法不会改变。我在之前已经考虑过这个问题这里,并且接受的答案起作用,但是对于枚举和枚举值的两个不同名称的需要正在杀死这两种方法的兼容性。这使得它当然不能使用替换C ++ 0x代码。我想知道如果一些 #undef #define 欺骗可以解决这个问题,让我 em> enum class 类似的语法(也许没有严格的类型安全等),但至少相同的语法。谢谢!

with all the bells and whistles this brings. I would like to make this code compatible with MSVC 2010, to the effect that the usage syntax does not change. I already pondered on this before here, and the accepted answer works, but the need for the two different names fo the enum and the enum values is killing the compatibility of the two approaches. This makes it of course unusable to replace the C++0x code as is. I wondered if some #undef and #define trickery could work around this, allowing me to use enum class-like syntax (perhaps without the strict type safety etc.), but at least the same syntax. Thanks!

推荐答案

我刚刚发现了一个问题,詹姆斯的好的黑客(我以前一直使用)问题。当我试图为my_enum定义一个流运算符时,我发现了这个问题。

I just discovered a problem with James' good hack (which I have heretofore been using), and a fix to the problem. I discovered the problem when I tried to define a stream operator for my_enum.

#include <iostream>

struct my_enum {
    enum type { 
        value1, 
        value2 
    };

    my_enum(type v) : value_(v) { }

    operator type() const { return value_; }

private:

    type value_;
};

std::ostream&
operator<<(std::ostream& os, my_enum v)
{
    return os << "streaming my_enum";
}

int main()
{
    std::cout << my_enum::value1 << '\n';
}

输出为:

0

问题是 my_enum :: value1 具有与 my_enum 不同的类型。

The problem is my_enum::value1 has different type than my_enum. Here's a hack to James' hack that I came up with.

struct my_enum
{
    static const my_enum value1;
    static const my_enum value2;

    explicit my_enum(int v) : value_(v) { }

    // explicit // if you have it!
       operator int() const { return value_; }

private:

    int value_;
};

my_enum const my_enum::value1(0);
my_enum const my_enum::value2(1);

注意:


  1. 除非
  2. 允许对底层整数类型进行显式转换。但隐式转换不是。尽力而为。

  3. 由于需要枚举值两次,所以这个黑客更像是詹姆斯的皮克。我希望没有scoped枚举支持的编译器快速灭绝!

  1. Unless otherwise specified by an enum-base, the underlying type of a scoped enumeration is int.
  2. Explicit conversions to and from the underlying integral type are allowed. But implicit conversions are not. Do your best.
  3. This hack is more of a pita than James' because of the need to enumerate the values twice. I'm hoping compilers without scoped enum support rapidly become extinct!

这篇关于“枚举类”仿真或固体替代MSVC 10.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆