Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
};

Which allows the use like this:

my_enum e = my_enum::value1;

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
100 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 << '
';
}

The output is:

0

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);

Notes:

  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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...