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++).

3
  • 2
    Please post a code example and the error from gcc. Nov 23, 2011 at 3:42
  • @ChrisF Could you explain why you’ve voted to close this question after the asker provided relevant information?
    – user557219
    Nov 24, 2011 at 2: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 4, 2013 at 5:55

1 Answer 1

1

Just convert it using static_cast:

uiSwipeRightDownRecogniser.direction = static_cast<UISwipeDirection>(Right | Down);
4
  • 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, 2011 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, 2011 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 4, 2013 at 6: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 4, 2013 at 6:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.