Re: [問題] C 語言下有類似 Template 的功能嗎?
如果有裝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()
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.56.185
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1495609168.A.130.html
※ 編輯: loveflames (60.248.56.185), 05/24/2017 15:06:17
推
05/24 16:14, , 1F
05/24 16:14, 1F
→
05/24 16:14, , 2F
05/24 16:14, 2F
→
05/24 16:15, , 3F
05/24 16:15, 3F
→
05/24 16:15, , 4F
05/24 16:15, 4F
是,這裡表示從0開始,到2結束
→
05/24 16:16, , 5F
05/24 16:16, 5F
str是隨便取的名稱,這樣用是因為macro遇到#跟##不會展開
所以要分兩行才能展開
→
05/24 16:17, , 6F
05/24 16:17, 6F
→
05/24 16:18, , 7F
05/24 16:18, 7F
→
05/24 16:19, , 8F
05/24 16:19, 8F
\是連結下一行,你用gcc -E去看就會知道展開成一行
其實有不展開成一行的方式,比較麻煩
※ 編輯: loveflames (60.248.56.185), 05/24/2017 16:41:33
推
05/24 16:56, , 9F
05/24 16:56, 9F
推
05/24 18:00, , 10F
05/24 18:00, 10F
→
05/24 18:01, , 11F
05/24 18:01, 11F
推
05/24 23:14, , 12F
05/24 23:14, 12F
→
05/24 23:48, , 13F
05/24 23:48, 13F
→
05/24 23:48, , 14F
05/24 23:48, 14F
→
05/24 23:49, , 15F
05/24 23:49, 15F
→
05/25 09:02, , 16F
05/25 09:02, 16F
→
05/25 09:02, , 17F
05/25 09:02, 17F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):