1

I tried below, but compiler does not understand it:

//Foo.mm
id anObjOfTypeFoo;
Foo* obj = (Foo*) anObjOfTypeFoo; //ERROR: must use __bridge

Foo* obj = (__bridge Foo*) anObjOfTypeFoo; //OKAY

Foo* obj = static_cast<__bridge Foo*> (anObjOfTypeFoo); //ERROR

Foo* obj = __bridge (static_cast<Foo*> (anObjOfTypeFoo)); //ERROR

Since Objective-C code is effectively compiled by a C++ compiler for a .mm compilation unit, it should really not have problems to bridge the casts of C++. Can someone shed light on this please?

jscs
  • 63,694
  • 13
  • 151
  • 195
Viren
  • 2,161
  • 22
  • 27
  • Well, __bridge offers a cast between Objective-C pointers and Core Foundation objects. Why would you need a static_cast anyways? – Alejandro Feb 18 '14 at 01:25
  • 1
    My core logic is written in C++ and I'm just putting a UI code on top of it for iOS client. And static_cast is preferred over normal C-style cast because of many reasons, prominent being given its' safety. [ http://stackoverflow.com/questions/103512/in-c-why-use-static-castintx-instead-of-intx ] – Viren Feb 18 '14 at 02:08
  • Please correct me if I am mistaken, but I do not think you can static_cast a Core Foundation object to an Objective C object with a simple static_cast. It used to be that way (well, it used to be a normal C-style cast), but the new ARC policies enforce __bridge'ing. – Alejandro Feb 18 '14 at 03:35
  • Even I don't know what is the correct way to handle static_cast with __bridge. :( Also not sure why someone added automatic-ref-counting to this question. lol – Viren Feb 18 '14 at 03:39
  • 1
    __bridge was actually mainly driven by ARC. From what I understand, and I did a detailed write up here (http://stackoverflow.com/questions/14207960/arc-bridge-modifiers-demystified/14207961#14207961 ) about __bridge modifiers, __bridge is almost like a plain-old cast. So mixing them together doesn't make sense. – Alejandro Feb 18 '14 at 03:44
  • 1
    `Foo* obj = (Foo*) anObjOfTypeFoo; //ERROR: must use __bridge` That's not possible. Unless `Foo` is not an Objective-C class. If `Foo` is an Objective-C class, there should be no error with or without the cast. – newacct Feb 19 '14 at 10:53

1 Answers1

3

Too bad static_cast come from C++, it doesn't understand Objective-C classes. You can't even cast from NSString to NSMutableString.

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22