How to check if a task is in a macro parameter?

How can we check if there is an assignment in a macro parameter like below?

define:

#define value(x) {...}

      

call:

case a: value( a = 10 )
case b: value( 10 )

      

what i want to do is implement the enumeration of the line below:

#define STR_ENUM_DICT_ITEM_(value)  [@((MethodX value)) stringValue]:@#value,
#define STR_ENUM_DICT_ITEM(idx, value)  STR_ENUM_DICT_ITEM_(value)         

#define STR_ENUM(type, name, ...) \
typedef NS_ENUM (type, name){__VA_ARGS__}; \
NSString *name##_S(type value) \
{ \
    static NSDictionary   *values; \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        values = @{ \
            metamacro_foreach(STR_ENUM_DICT_ITEM, , __VA_ARGS__) \
        }; \
    }); \
    return [values valueForKey:[@(value)stringValue]]; \
}  

STR_ENUM(NSUInteger, MethodX,
   Method1 = 100// this is comment
   , Method2
   , Method3 = Method1
);

      

so I need to check if the job is in the parameter or in some other way can get the value (Method1 = 100) or (Method3 = Method1), which returns 100, 100.

+3


source to share


2 answers


Not very efficient in terms of performance, but it works:

#define value(x) \
  do { \
    assert(!strchr(#x, '=')); \
    /* rest of macro */ \
  } while (0)

      



This is a simple example covering only two cases provided by the OP. However, by using an operator #

to convert a macro argument to a "string", you can create as complex rules for testing as you like.

+2


source


Can you elaborate on which cases you want to distinguish? What about

value(a)
value(a+2)
value(a==10)
value(a<=10)
value('=')

      

?

What do you want to do if it contains a task? Compilation error or something else?



For compilation error, I managed to do the following job

#define check(a) if (a==a);

int main() {
   int a;
   check(10);
   check(a);
   check(a+2);
   check(a==10);
   check(a<=10);
   check('=');
   check(a=10);
   return 0;
}

      

Every macro except compilation a=10

. The latter turns into a=10==a=10

one that doesn't compile.

+2


source







All Articles