Created
December 2, 2014 20:25
-
-
Save OneSadCookie/bd65bcfac661e583b9a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
template<class T> | |
T *objc_faithcast(id u) | |
{ | |
assert([u isKindOfClass:[T class]]); | |
return reinterpret_cast<T *>(u); | |
} | |
template<class T, class U> | |
T *objc_faithcast(U *u) | |
{ | |
assert([[T class] isSubclassOfClass:[U class]]); | |
assert([u isKindOfClass:[T class]]); | |
return reinterpret_cast<T *>(u); | |
} | |
template<class T> | |
T *objc_maybecast(id u) | |
{ | |
return [u isKindOfClass:[T class]] ? reinterpret_cast<T *>(u) : nil; | |
} | |
template<class T, class U> | |
T *objc_maybecast(U *u) | |
{ | |
assert([[T class] isSubclassOfClass:[U class]]); | |
return [u isKindOfClass:[T class]] ? reinterpret_cast<T *>(u) : nil; | |
} | |
int main() | |
{ | |
NSString *s = [NSMutableString new]; | |
NSMutableString *ms = objc_faithcast<NSMutableString>(s); | |
assert(s == ms); | |
id i = [NSMutableString new]; | |
NSMutableString *ms2 = objc_faithcast<NSMutableString>(i); | |
assert(i == ms2); | |
NSString *s2 = reinterpret_cast<id>(@3); | |
NSMutableString *ms3 = objc_maybecast<NSMutableString>(s2); | |
assert(!ms3); | |
id i2 = @3; | |
NSMutableString *ms4 = objc_maybecast<NSMutableString>(i2); | |
assert(!ms4); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment