How should C bitflag enumerations be translated into C++?

后端 未结 3 725
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 14:58

C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn\'t true: only in C do i

相关标签:
3条回答
  • 2021-01-14 15:20

    Either leave the result as an int or static_cast:

    Foo x = static_cast<Foo>(Foo_First | Foo_Second); // not an error in C++
    
    0 讨论(0)
  • 2021-01-14 15:27

    It sounds like an ideal application for a cast - it's up to you to tell the compiler that yes, you DO mean to instantiate a Foo with a random integer.

    Of course, technically speaking, Foo_First | Foo_Second isn't a valid value for a Foo.

    0 讨论(0)
  • 2021-01-14 15:31

    Why not just cast the result back to a Foo?

    Foo x = Foo(Foo_First | Foo_Second);
    

    EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns a Foo:

    Foo operator|(Foo a, Foo b)
    {
        return Foo(int(a) | int(b));
    }
    

    The int casts are there to prevent undesired recursion.

    0 讨论(0)
提交回复
热议问题