如果有裝boost的話,可以這樣做,gcc相容boost.preprocessor
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/iteration/local.hpp>
//這裡放每個成員的名稱,此例子為3個成員
#define t (aaa,bbb,ccc)
//#的展開規則,所以得分兩行寫
#define str(s) _str(s)
#define _str(s) #s
//BOOST_PP_LOCAL_MACRO是每一輪的展開,n遞增
//這裡為函數本體,BOOST_PP_TUPLE_ELEM從上面的t抓token出來,從第一個抓起
#define BOOST_PP_LOCAL_MACRO(n) int BOOST_PP_CAT(get_,BOOST_PP_TUPLE_ELEM(3,n,t))(struct obj_s *self){\
int err_code = checkByMode(self,\
BOOST_PP_CAT(&_common_update_attr_,BOOST_PP_TUPLE_ELEM(3,n,t)),\
str(BOOST_PP_CAT(common_get_,BOOST_PP_TUPLE_ELEM(3,n,t))));\
if (err_code < 0){\
return err_code;\
}\
return (int)self-> BOOST_PP_TUPLE_ELEM(3,n,t);\
}
//表示BOOST_PP_LOCAL_MACRO為0->1->2的展開,即3個成員
#define BOOST_PP_LOCAL_LIMITS (0,2)
//實際展開
#include BOOST_PP_LOCAL_ITERATE()