数组初始化宏 [英] Array Initialization Macro

查看:130
本文介绍了数组初始化宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图提供一个宏来执行以下操作,

I am trying to come up with a macro to do something like the following,

MY_MACRO(type,name,args...)
MY_MACRO(int,_array,1,2,3)

扩展为

int _array[] = {1,2,3};
coll* __array = my_call(&array[0],&array[1],&array[2]);

有/没有编译器特定的魔术可能吗?

is this possible with/without compiler specific magic?

my_call期望可变数量的参数,并且我不想直接传递数组。

my_call expects variable number of arguments and I do not want to pass the array directly.

编辑:我已经在使用以下SO问题的可接受答案对于var args,

I am already using the accepted answer from the following SO question for var args,

宏返回在C语言中给出的参数个数?

所以我可以找到

推荐答案

您可以从(C99,而不是GCC特定)开始:

You can start with (C99, not GCC-specific):

#define MY_MACRO(type, name, ...) \
  type name[] = {__VA_ARGS__};

my_call 部分会更困难;网上有一些宏可以计算参数的数量,但是您需要使用Boost.Preprocessor之类的东西(应该在C语言中运行)才能将 my_call 应用于数组。您最多有多少个元素?您可能想要以下内容:

The my_call part will be more difficult; there are macros online that can count the number of arguments, but you will need something like Boost.Preprocessor (which should work in C) to apply my_call to the consecutive elements of the array. How many elements do you have as a maximum? You might want something like:

#define COUNT(...) COUNT2(__VA_ARGS__, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define COUNT2(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, count, ...) count
#define PP_CAT(a, b) PP_CAT2(a, b)
#define PP_CAT2(a, b) a ## b
#define CALL_MY_FUNC(arr, ...) my_call(PP_CAT(ITER_, COUNT(__VA_ARGS__))(arr));
#define ITER_0(arr) /**/
#define ITER_1(arr) (arr)
#define ITER_2(arr) (arr), ITER_1((arr) + 1)
#define ITER_3(arr) (arr), ITER_2((arr) + 1)
#define ITER_4(arr) (arr), ITER_3((arr) + 1)

,依此类推。

这篇关于数组初始化宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆