Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Parameters with C++ Macros

Tags:

c++

macros

Is there some way of getting optional parameters with C++ Macros? Some sort of overloading would be nice too.

like image 506
Cenoc Avatar asked Jun 15 '10 16:06

Cenoc


People also ask

Can you have optional parameters in C?

C does not support optional parameters.

What is macro with parameters in C?

Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.

How use macros with parameters?

Macro parameter values are character sequences of no formal type, and they are comma delimited. There is no way to pass in a comma as part of a parameter value. The number of parameters passed can be less than, greater than, or equal to the number of parameters that the macro value is designed to receive.

Can parameters be optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.


1 Answers

Here's one way to do it. It uses the list of arguments twice, first to form the name of the helper macro, and then to pass the arguments to that helper macro. It uses a standard trick to count the number of arguments to a macro.

enum {     plain = 0,     bold = 1,     italic = 2 };  void PrintString(const char* message, int size, int style) { }  #define PRINT_STRING_1_ARGS(message)              PrintString(message, 0, 0) #define PRINT_STRING_2_ARGS(message, size)        PrintString(message, size, 0) #define PRINT_STRING_3_ARGS(message, size, style) PrintString(message, size, style)  #define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 #define PRINT_STRING_MACRO_CHOOSER(...) \     GET_4TH_ARG(__VA_ARGS__, PRINT_STRING_3_ARGS, \                 PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS, )  #define PRINT_STRING(...) PRINT_STRING_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)  int main(int argc, char * const argv[]) {     PRINT_STRING("Hello, World!");     PRINT_STRING("Hello, World!", 18);     PRINT_STRING("Hello, World!", 18, bold);      return 0; } 

This makes it easier for the caller of the macro, but not the writer.

like image 60
Derek Ledbetter Avatar answered Sep 20 '22 02:09

Derek Ledbetter