From: Douglas Gregor
Use __has_feature(objc_fixed_enum) to determine whether support for fixed underlying types is available in Objective-C.
+ +Clang provides interoperability between C++11 lambdas and
+blocks-based APIs, by permitting a lambda to be implicitly converted
+to a block pointer with the corresponding signature. For example,
+consider an API such as NSArray
's array-sorting
+method:
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;+ +
NSComparator
is simply a typedef for the block pointer
+NSComparisonResult (^)(id, id)
, and parameters of this
+type are generally provided with block literals as arguments. However,
+one can also use a C++11 lambda so long as it provides the same
+signature (in this case, accepting two parameters of type
+id
and returning an NSComparisonResult
):
+ NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", + @"String 02"]; + const NSStringCompareOptions comparisonOptions + = NSCaseInsensitiveSearch | NSNumericSearch | + NSWidthInsensitiveSearch | NSForcedOrderingSearch; + NSLocale *currentLocale = [NSLocale currentLocale]; + NSArray *sorted + = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { + NSRange string1Range = NSMakeRange(0, [s1 length]); + return [s1 compare:s2 options:comparisonOptions + range:string1Range locale:currentLocale]; + }]; + NSLog(@"sorted: %@", sorted); ++ +
This code relies on an implicit conversion from the type of the +lambda expression (an unnamed, local class type called the closure +type) to the corresponding block pointer type. The conversion +itself is expressed by a conversion operator in that closure type +that produces a block pointer with the same signature as the lambda +itself, e.g.,
+ ++ operator NSComparisonResult (^)(id, id)() const; ++ +
This conversion function returns a new block that simply forwards +the two parameters to the lambda object (which it captures by copy), +then returns the result. The returned block is first copied (with +Block_copy) and then autoreleased. As an optimization, if a +lambda expression is immediately converted to a block pointer (as in +the first example, above), then the block is not copied and +autoreleased: rather, it is given the same lifetime as a block literal +written at that point in the program, which avoids the overhead of +copying a block to the heap in the common case.
+