代码之家  ›  专栏  ›  技术社区  ›  Curious

连接宏中的前n-1个参数

  •  0
  • Curious  · 技术社区  · 7 年前

    我需要编写一个如下所示的宏

    MACRO(one, name, "some string");
    

    如果宏有n个参数,我需要能够连接第一个参数 n-1 带下划线的参数。例如,上面的调用将扩展到

    std::string one_name{"some string"};
    

    同样,如果我有这样的东西

    MACRO(one, two, name, "some string");
    

    我应该得到

    std::string one_two_name{"some string"};
    

    这有可能吗?


    免责声明 :我无法摆脱对这个宏的使用。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Jarod42    7 年前

    #define COUNT_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...)    N
    #define COUNT(...)   COUNT_N(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    // Warning: COUNT() return 1 (as COUNT(A)) :-/
    
    #define IDENTITY(N) N
    #define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))
    
    #define F_1(_) static_assert(false, "Not enough argument")
    #define F_2(a, s) std::string a = s;
    #define F_3(a, b, s) std::string a ## _ ## b = s;
    #define F_4(a, b, c, s) std::string a ## _ ## b ## _ ## c= s;
    #define F_5(a, b, c, d, s) std::string a ## _ ## b ## _ ## c ## _ ## d= s;
    #define F_6(a, b, c, d, e, s) std::string a ## _ ## b ## _ ## c ## _ ## d ## _ ## e = s;
    #define F_7(a, b, c, d, e, f, s) std::string a ## _ ## b ## _ ## c ## _ ## d ## _ ## e ## _ ## f= s;
    #define F_8(a, b, c, d, e, f, g, s) std::string a ## _ ## b ## _ ## c ## _ ## d ## _ ## e ## _ ## f ## _ ## g = s;
    
    #define DISPATCH(N) F_ ## N
    
    #define Macro(...) IDENTITY(APPLY(DISPATCH, COUNT(__VA_ARGS__)))(__VA_ARGS__)
    

    Demo