Skip to content

Instantly share code, notes, and snippets.

@dhh1128
Last active October 5, 2019 11:41
Show Gist options
  • Select an option

  • Save dhh1128/d1dd24b492819c65f1e1 to your computer and use it in GitHub Desktop.

Select an option

Save dhh1128/d1dd24b492819c65f1e1 to your computer and use it in GitHub Desktop.

Revisions

  1. dhh1128 revised this gist Nov 25, 2014. 1 changed file with 6 additions and 3 deletions.
    9 changes: 6 additions & 3 deletions for_each_macro
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,9 @@
    // Accept any number of args >= N, but expand to just the Nth one. Here,
    // N == 6.
    // Accept any number of args >= N, but expand to just the Nth one.
    // Here, N == 6.
    #define _GET_NTH_ARG(_1, _2, _3, _4, _5, N, ...) N

    // Define some macros to help us create overrides based on the
    // arity of a for-each-style macro.
    #define _fe_0(_call, ...)
    #define _fe_1(_call, x) _call(x)
    #define _fe_2(_call, x, ...) _call(x) _fe_1(_call, __VA_ARGS__)
    @@ -12,10 +14,11 @@
    * Provide a for-each construct for variadic macros. Supports up
    * to 4 args.
    *
    * Example usage:
    * Example usage1:
    * #define FWD_DECLARE_CLASS(cls) class cls;
    * CALL_MACRO_X_FOR_EACH(FWD_DECLARE_CLASS, Foo, Bar)
    *
    * Example usage 2:
    * #define START_NS(ns) namespace ns {
    * #define END_NS(ns) }
    * #define MY_NAMESPACES System, Net, Http
  2. dhh1128 created this gist Nov 22, 2014.
    28 changes: 28 additions & 0 deletions for_each_macro
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    // Accept any number of args >= N, but expand to just the Nth one. Here,
    // N == 6.
    #define _GET_NTH_ARG(_1, _2, _3, _4, _5, N, ...) N

    #define _fe_0(_call, ...)
    #define _fe_1(_call, x) _call(x)
    #define _fe_2(_call, x, ...) _call(x) _fe_1(_call, __VA_ARGS__)
    #define _fe_3(_call, x, ...) _call(x) _fe_2(_call, __VA_ARGS__)
    #define _fe_4(_call, x, ...) _call(x) _fe_3(_call, __VA_ARGS__)

    /**
    * Provide a for-each construct for variadic macros. Supports up
    * to 4 args.
    *
    * Example usage:
    * #define FWD_DECLARE_CLASS(cls) class cls;
    * CALL_MACRO_X_FOR_EACH(FWD_DECLARE_CLASS, Foo, Bar)
    *
    * #define START_NS(ns) namespace ns {
    * #define END_NS(ns) }
    * #define MY_NAMESPACES System, Net, Http
    * CALL_MACRO_X_FOR_EACH(START_NS, MY_NAMESPACES)
    * typedef foo int;
    * CALL_MACRO_X_FOR_EACH(END_NS, MY_NAMESPACES)
    */
    #define CALL_MACRO_X_FOR_EACH(x, ...) \
    _GET_NTH_ARG("ignored", ##__VA_ARGS__, \
    _fe_4, _fe_3, _fe_2, _fe_1, _fe_0)(x, ##__VA_ARGS__)