5

Cocoa utilises typedef-ed anonymous enum bitfields.

I'm using objective-C++, for better & worse. Inside a .mm file I need to assign 2 bits (bitwise inclusive OR) to a property of the type of one of these enum bitfield types. The libc++ compiler won't have it because it won't give an rvalue of type int to a property of that typedef-ed anonymous enum bitfield.

I understand there is a size difference of enums between C & C++. So what is the work-around for this situation?

My line performing the assignment is akin to:

    uiSwipeRightDownRecogniser.direction = Right | Down;

The definition of the bitfield is akin to:

    typedef enum 
    {
        Right = 1 << 0,
        Left  = 1 << 1,
        Up    = 1 << 2,
        Down  = 1 << 3
    } UISwipeDirection;

The error is:

Cannot initialize a parameter of type 'UISwipeDirection' with an rvalue of type 'int'

That kind of assignment works in a .m file, but not a .mm.

The compiler is Apple's LLVM 3.0 (using libc++).

codey
  • 71
  • 3
  • 2
    Please post a code example and the error from gcc. – Miguel Grinberg Nov 23 '11 at 03:42
  • @ChrisF Could you explain why you’ve voted to close this question **after** the asker provided relevant information? –  Nov 24 '11 at 02:24
  • @ChrisF Not to pick on you particularly out of all the people who voted to close this, but this is absolutely a real question. Had this exact problem when converting some of my *.m* files to *.mm* files. – Matt Mc Jul 04 '13 at 05:55

1 Answers1

1

Just convert it using static_cast:

uiSwipeRightDownRecogniser.direction = static_cast<UISwipeDirection>(Right | Down);
justin
  • 104,054
  • 14
  • 179
  • 226
  • Thank you very much. It works of course. I had seen the casting before but had seen other things that lead me to believe it was not really safe. On a scale of 1 - 10, how safe am I doing the cast? – codey Nov 23 '11 at 11:57
  • 1
    @codey this conversion is fine. there is no loss/narrowing. it's analogous to `(UISwipeDirection)(Right | Down)` in C. – justin Nov 23 '11 at 12:12
  • @justin Wondering if you can refer me to data as to why this is? Your solution worked perfectly, but I'm wondering why it was necessary when I was assigning a clearly typed value (one of the enum bitmask values) to something typed as the enum bitmask. Confusing-much. – Matt Mc Jul 04 '13 at 06:01
  • @MattMc most C is valid C++, but not this. in C++, the arithmetic operation results in an `int`. in C++, an `int` is not implicitly convertible to an `enum` type. thus, the explicit conversion is required (e.g. `static_cast<>`). this is stronger typing, which prevents you from saying `UISwipeDirection dir = -2;`. overloading the operators is permitted. – justin Jul 04 '13 at 06:55