Skip to content

Instantly share code, notes, and snippets.

@yugui
Last active May 7, 2016 02:08
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 yugui/6dbf648b5bc956b43a8d to your computer and use it in GitHub Desktop.
Save yugui/6dbf648b5bc956b43a8d to your computer and use it in GitHub Desktop.
Objective C99++11
g++ -framework Foundation -std=gnu++14 -lobjc test.mm
#import <Foundation/NSObject.h>
#include <iostream>
struct {
int a;
int b;
int c;
} a;
int func(decltype(a)&& b) {
return b.c;
}
int main() {
NSObject* obj = [[NSObject alloc] init];
std::cout << func((typeof(a)){ .b = 1, .c = 2}) << std::endl;
return 0;
}
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
#include <iomanip>
#include <iostream>
#include <iterator>
template <typename T>
class nsarray_iter
: public std::iterator<std::forward_iterator_tag, T, NSUInteger> {
public:
explicit nsarray_iter(NSArray<T>* array)
: nsarray_iter(array, 0) {}
nsarray_iter(NSArray<T>* array, NSUInteger i)
: array_(array), i_(i) {
[array_ retain];
}
nsarray_iter(const nsarray_iter<T>& orig)
: nsarray_iter(orig.array_, orig.i_) {}
~nsarray_iter() {
[array_ release];
}
template <typename U>
nsarray_iter<T>& operator=(const nsarray_iter<U>& rhs) {
[array_ release];
array_ = rhs.array_;
i_ = rhs.i_;
return *this;
}
const T& operator *() const {
return [array_ objectAtIndex: i_];
}
T& operator *() {
return [array_ objectAtIndex: i_];
}
nsarray_iter operator ++(int) {
nsarray_iter orig{array_, i_};
++i_;
return orig;
}
nsarray_iter& operator ++() {
++i_;
return *this;
}
private:
NSArray<T>* const array_;
NSUInteger i_;
};
template <typename T>
nsarray_iter<T> begin(NSArray<T>* array) {
return nsarray_iter<T>(array);
}
template <typename T>
nsarray_iter<T> end(NSArray<T>* array) {
return nsarray_iter<T>(array, [array count]);
}
std::ostream& operator <<(std::ostream& os, id obj) {
auto* const str = [obj description];
if (const auto len = [str length]) {
return os << std::setw(len) << [str UTF8String];
} else {
return os;
}
}
static struct {
id prefix;
NSArray<NSNumber*>* elems;
id suffix;
} a;
void printList(decltype(a)&& list) {
if (list.prefix != nil) {
std::cout << list.prefix;
std::cout << ",";
}
for (NSNumber* val : list.elems) {
std::cout << val << ",";
}
std::cout << list.suffix << std::endl;
}
int main() {
NSArray<NSNumber*> *elems = [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt: 1], [NSNumber numberWithUnsignedInt: 2], nil];
printList((typeof(a)){ .elems = elems, .suffix = [NSString stringWithUTF8String:"done"]});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment