Frage

I was getting tired of repeating types when writing things like this:

NSDictionary* d = @{@"so": [NSNumber numberWithInt:index]),
                    @"much": [NSNumber numberWithBool:accepted]),
                    @"repeat": [NSNumber numberWithDouble:height]};

So I defined a generic macro (a new feature in C11):

#define box(X) _Generic((X), \
char: boxChar, \
unsigned char: boxUnsignedChar, \
short: boxShort, \
unsigned short: boxUnsignedShort, \
int: boxInt, \
unsigned int: boxUnsignedInt, \
long: boxLong, \
unsigned long: boxUnsignedLong, \
long long: boxLongLong, \
unsigned long long: boxUnsignedLongLong, \
float: boxFloat, \
double: boxDouble, \
BOOL: boxBool \
)(X)

... implement type-specific box methods as well ...

So that I could write things like this:

NSDictionary* d = @{@"so": box(index),
                    @"much": box(accepted),
                    @"shorter": box(height)};

Is this a good idea? Can I expect others to be able to build the code? Will they hate it for not being standard?

War es hilfreich?

Lösung

What you are doing is already provided by Objective-C called Boxed Expressions

with example taken from llvm website

// numbers.
NSNumber *smallestInt = @(-INT_MAX - 1);  // [NSNumber numberWithInt:(-INT_MAX - 1)]
NSNumber *piOverTwo = @(M_PI / 2);        // [NSNumber numberWithDouble:(M_PI / 2)]

// enumerated types.
typedef enum { Red, Green, Blue } Color;
NSNumber *favoriteColor = @(Green);       // [NSNumber numberWithInt:((int)Green)]

// strings.
NSString *path = @(getenv("PATH"));       // [NSString stringWithUTF8String:(getenv("PATH"))]
NSArray *pathComponents = [path componentsSeparatedByString:@":"];

Andere Tipps

Self-answer: I didn't realize there's actually a standard syntax to do this. I'd tried @variable before, but actually I was supposed to use @(variable).

Which means that the answer to the question is: yes, they would hate it. But what exists is better anyways.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top