Skip to content

Instantly share code, notes, and snippets.

@OneSadCookie
Created December 2, 2014 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneSadCookie/bd65bcfac661e583b9a2 to your computer and use it in GitHub Desktop.
Save OneSadCookie/bd65bcfac661e583b9a2 to your computer and use it in GitHub Desktop.
#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