在C/C++中展开变元宏的参数并生成代码有什么解决方案吗?

bfrts1fy  于 7个月前  发布在  C/C++
关注(0)|答案(2)|浏览(90)

在C/C中利用宏实现代码的批量生成
我想在C/C
中实现一个variadice宏,它可以作为一段代码展开。任何数量的参数都可以传递到宏中,宏将如以下示例展开:

#define DECLARE_LIST(...) // definition of the macro

DECLARE_LIST(a)
/* unrollig as
void funcA() {
    declare(a);
}

void funcB() {
    load(a);
}
*/

DECLARE_LIST(a, b, c)
/* unrollig as
void funcA() {
    declare(a);
    declare(b);
    declare(c);
}

void funcB() {
    load(a);
    load(b);
    load(c);
}
*/

DECLARE_LIST(a, b, c, d, ...) // for any number of macro parameter

字符串

xuo3flqw

xuo3flqw1#

这将是C++使用可变参数模板的答案

#include <iostream>

void load(int value)
{
    std::cout << value << "\n";
}

// c++ 17
template<typename... args_t>
void load_all(args_t&&... args)
{
    // use a fold expression 
    // creates one line of code for each argument passed in
    (load(std::forward<args_t>(args)),...);
}

// c++20
void load_all_cpp20(auto&&... args)
{
    (load(std::forward<decltype(args)>(args)),...);
}

int main()
{
    int a{1};
    int b{2};
    load_all(a,b,3,4,5);
    return 0;
}

字符串
这段代码将输出1,2,3,4,5(在新的行上)

3hvapo4f

3hvapo4f2#

这可能是一个C/C++答案(使用X macro):

#define DECL(x) declare(x);
#define LOAD(x) load(x);
#define DECLARE_LIST(f1,f2,z) void f1() { z(DECL) } void f2() { z(LOAD) } 

#define LIST_1(_) _(a)
DECLARE_LIST(funcA,funcB,LIST_1) 

#define LIST_2(_) _(a)_(b)_(c)
DECLARE_LIST(funcC,funcD,LIST_2)

字符串
我已经把函数名作为参数取出来了,但这不是必需的。

相关问题