c++ - Can macros be overloaded by number of arguments? -


how this work? how can c99/c++11 variadic macro implemented expand different things on sole basis of how many arguments given it?

(edit: see end ready-made solution.)

to overloaded macro, first need macro selects between several implementations. part doesn't use variadic macro. variadic macro generically counts arguments produces selector. plugging argument count dispatcher produces overloaded macro.

caveat: system cannot tell difference between 0 , 1 arguments because there is no difference between no argument, , single empty argument. both macro().


to select between implementations, use macro catenation operator series of function-like macros.

#define select( selector, ... ) impl ## _ ## selector( __va_args__ ) #define impl_1() meh #define impl_2( abc, xyz ) # abc "wizza" xyz() //etc  // usage: select( 1 ) => impl_1() => meh //        select( 2, huz, bar ) => impl_2( huzza, bar ) => "huz" "wizza" bar() 

because ## operator suppresses macro expansion of arguments, it's better wrap in macro.

#define cat( a, b ) ## b #define select( name, num ) cat( name ## _, num ) 

to count arguments, use __va_args__ shift arguments (this clever part):

#define get_count( _1, _2, _3, _4, _5, _6 /* ad nauseam */, count, ... ) count #define va_size( ... ) get_count( __va_args__, 6, 5, 4, 3, 2, 1 ) 

library code:

#define cat( a, b ) ## b #define select( name, num ) cat( name ## _, num )  #define get_count( _1, _2, _3, _4, _5, _6 /* ad nauseam */, count, ... ) count #define va_size( ... ) get_count( __va_args__, 6, 5, 4, 3, 2, 1 )  #define va_select( name, ... ) select( name, va_size(__va_args__) )(__va_args__) 

usage:

#define my_overloaded( ... ) va_select( my_overloaded, __va_args__ ) #define my_overloaded_1( x ) foo< x > #define my_overloaded_2( x, y ) bar< x >( y ) #define my_overloaded_3( x, y, z ) bang_ ## x< y >.z() 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -