初始化使用宏用C未知大小的二维数组 [英] Initialize a 2D array of unknown size using macros in C
本文介绍了初始化使用宏用C未知大小的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我工作,需要我去一个2维数组文本传递到像这样我的宏的一个小宏项目: myMacro({{0,1,2},{2,1 ,0}})
。无需通过数组文本宏的大小,有没有办法把它扩展到以下内容: INT [2] [3] = {{0,1,2},{ 2,1,0}}
或等价的东西(即$ p $任何初始化pserves阵列的形状将工作)?感谢您事先的任何帮助。
解决方案
的#include<升压/ preprocessor /元组/ size.hpp>
#包括LT&;升压/ preprocessor /元组/ elem.hpp>
#包括LT&;升压/ preprocessor /可变参数/ to_seq.hpp>
#包括LT&;升压/ preprocessor / SEQ / for_each.hpp>#定义VA(...)__VA_ARGS__
#定义TRANS(R,数据,ELEM){VA ELEM},#定义myMacro(姓名,ARG)\\
INT名[BOOST_PP_TUPLE_SIZE(ARG)] [BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0,ARG))= \\
{BOOST_PP_SEQ_FOR_EACH(TRANS,BOOST_PP_VARIADIC_TO_SEQ ARG)}诠释主(){
myMacro(一,((1,2,3),(4,5,6))); // = GT;诠释一个[2] [3] = {{1,2,3},{4,5 ,6},};
返回0;
}
I was working on a small macro project that requires me to pass a 2 dimensional array literal to one of my macros like so: myMacro({{0, 1, 2}, {2, 1, 0}})
. Without having to pass the size of the array literal to the macro, is there a way to have it expand to the following: int[2][3] = { {0, 1, 2}, {2, 1, 0} }
or something equivalent (any initialization that preserves the shape of the array will work)? Thanks in advance for any help
解决方案
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#define VA(...) __VA_ARGS__
#define TRANS(r, data, elem) { VA elem},
#define myMacro(name, arg)\
int name[BOOST_PP_TUPLE_SIZE(arg)][BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0,arg))] = \
{ BOOST_PP_SEQ_FOR_EACH(TRANS, , BOOST_PP_VARIADIC_TO_SEQ arg)}
int main(){
myMacro(a, ((1,2,3),(4,5,6)) );//=>int a[2][3] = { { 1,2,3}, { 4,5,6}, };
return 0;
}
这篇关于初始化使用宏用C未知大小的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文