A more general solution is to use reference_wrapper<T> instead of a custom structure. The end result is similar.
Then again, if you only need to save one element, you will not get many advantages over pointers, going either to the structure or to this shell. (Thanks, Georg!)
I used Georg's answer as a starting point for an example:
// This bare interface can be used from regular Objective-C code, // useful to pass around as an opaque handle @interface A : NSObject @end // This interface can be shown to appropriate Objective-C++ code @interface A (Private) // @interface A () if it just for this class .mm file - (id)initWithRef:(SomeClass &)ref; @property (readonly, nonatomic) SomeClass &ref; @end @implementation A { reference_wrapper<SomeClass> *_refWrapper; } - (id)init { // and/or throw an exception return nil; } - (id)initWithRef:(SomeClass &)ref { self = [super init]; if(self) { _refWrapper = new reference_wrapper<SomeClass>(ref); } return self; } - (SomeClass &)ref { // reference_wrapper<T> is implicitly convertible to T& return *_refWrapper; // This would also work: // return _refWrapper->get(); } - (void)dealloc { delete _refWrapper; } @end
This multi-header template is useful for passing an opaque descriptor in Objective-C code, giving Objective-C ++ the ability for multiple favorites (even if it's just an implementation of the objc class).
source share