Skip to content

Commit

Permalink
Add helper macro which enables function-like macro overload with 1 or…
Browse files Browse the repository at this point in the history
… 2 arguments.

Inspired by https://stackoverflow.com/a/11763277/

Warning: This requires support for variadic macros (`__VA_ARGS__`). These were officially added in C99 and C++11.
  • Loading branch information
dhebbeker committed Nov 9, 2023
1 parent 4eb46d6 commit 7771cf3
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions include/etl/macros.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,31 @@ SOFTWARE.
#define ETL_U16_STRING(X) ETL_CONCAT(u, ETL_STRINGIFY(X))
#define ETL_U32_STRING(X) ETL_CONCAT(U, ETL_STRINGIFY(X))

/**
* Resolves a function-like macro overload with 1 or 2 arguments.
*
* This macro can be used to call other function-like macros depending on the number of arguments
* provided by the caller.
*
* \param _1 is the first argument given to the called macro
* \param _2 is either the second argument given to the called macro
* or the name of the macro which takes to arguments
* \param SELECTED_MACRO_NAME is the name of the macro to be called
* \param ... is a non-empty list of arguments:
* The beginning of the list is a list of all macro names which accept less arguments than
* `SELECTED_MACRO_NAME`. This list may be empty.
* The last element in the list is a dummy argument. For example `""`.
* For compatibility reasons `...` should not be empty.
*
* Use this function-like macro as follows:
*
* #define TAKES1( a ) (a) //!< example macro which takes 1 argument
* #define TAKES2(a, b) (a+b) //!< example macro which takes 2 arguments
* #define TAKES_1or2(...) GET_MACRO_OVERLOAD2(__VA_ARGS__, TAKES2, TAKES1, "")(__VA_ARGS__)
*
* Now `TAKES_1or2()` can be called with 1 or 2 arguments.
*/
#define GET_MACRO_OVERLOAD2(_1, _2, SELECTED_MACRO_NAME, ...) SELECTED_MACRO_NAME

#endif

0 comments on commit 7771cf3

Please sign in to comment.