Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
any reason you don't like @(index)? –  Bryan Chen Nov 29 '13 at 1:34
    
@BryanChen I love it! I didn't know about it until you mentioned it just now. Question answered! –  Strilanc Nov 29 '13 at 1:55
add comment

2 Answers 2

up vote 3 down vote accepted

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:@":"];
share|improve this answer
    
Not sure if I should be embarrassed or elated. This is much better. –  Strilanc Nov 29 '13 at 2:34
    
Elated. Better to ask and learn. –  Clay Bridges May 31 at 12:07
add comment

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.

share|improve this answer
    
Also, literal constants don't need parens, @1, @YES. –  Clay Bridges May 31 at 12:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.