Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active March 30, 2022 02:47
Show Gist options
  • Save theoknock/fbea0ac829cc25c0951d65df3c682465 to your computer and use it in GitHub Desktop.
Save theoknock/fbea0ac829cc25c0951d65df3c682465 to your computer and use it in GitHub Desktop.
An adaptable functor (generic programming) using Blocks. An adaptable functor takes a function (or block) argument of any return type and number of arguments, and can be passed as an argument to other predicate/functors without modifying their return types and arguments (similar to the Adapter object-oriented programming design pattern).
/*
An adaptable functor (generic programming) using Blocks. An adaptable functor takes a function (or block) argument of any return type and number of arguments, and can be passed as an argument to other predicate/functors without modifying their return types and arguments (similar to the Adapter object-oriented programming design pattern).
*/
int (^int_blk)(int) = ^ (int i) {
printf("i == %d\n", i);
return (int)i;
};
const void * (^const __strong int_blk_ptr)(const int (^const __strong)(int)) = ^ (const int(^const __strong int_blk_ptr_t)(int)) { // Initializes block pointer blk_ptr using block parameter blk_ptr_t
printf("int_blk_ptr\n");
return Block_copy((const void *)CFBridgingRetain(int_blk_ptr_t));
};
((__bridge const int(^const __strong)(int))(int_blk_ptr(CFBridgingRelease((__bridge CFTypeRef _Nullable)(int_blk)))))(1); // Returns a pointer to int_blk_ptr_t (prints 'int_blk_ptr' to the console) using int_blk_ptr and invokes blk (prints 'i == 1' to the console)
// Using a block literal as a parameter instead of a block variable reference
int(^re_int_blk)(int) = CFBridgingRelease((^ (const int(^const __strong int_blk_ptr_t)(int)) { // Initializes block pointer blk_ptr using block parameter blk_ptr_t
printf("int_blk_ptr\n");
return Block_copy((const void *)CFBridgingRetain(int_blk_ptr_t));
}(^ (int i) {
printf("i == %d\n", i);
return (int)i;
})));
re_int_blk(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment