Re: [問題] C 語言下有類似 Template 的功能嗎?

看板C_and_CPP作者 (咕啾咕啾魔法陣)時間7年前 (2017/05/24 14:59), 7年前編輯推噓4(4013)
留言17則, 3人參與, 最新討論串2/2 (看更多)
如果有裝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
這有點猛!我還在google這段程式碼的細節,又有東西學
05/24 16:14, 1F

05/24 16:14, , 2F
的感覺好爽
05/24 16:14, 2F

05/24 16:15, , 3F
看得出用法和規律。想問些問題,裡面那個n的range是由
05/24 16:15, 3F

05/24 16:15, , 4F
#define BOOST_PP_LOCAL_LIMITS (0,2) 這行定義的嗎
05/24 16:15, 4F
是,這裡表示從0開始,到2結束

05/24 16:16, , 5F
然後 #define str(s) _str(s) 和 #define _str(s) #s
05/24 16:16, 5F
str是隨便取的名稱,這樣用是因為macro遇到#跟##不會展開 所以要分兩行才能展開

05/24 16:17, , 6F
這種用法有沒有網站的詳細解說?沒這樣寫過,有點生疏.
05/24 16:17, 6F

05/24 16:18, , 7F
最後那個BOOST_PP_LOCAL_M..內的 \ 為什麼需要寫上?
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
懂了,這跟console上輸入\的意思同樣嘛。
05/24 16:56, 9F

05/24 18:00, , 10F

05/24 18:01, , 11F
我看完這篇幫助滿大的 哈哈
05/24 18:01, 11F

05/24 23:14, , 12F
linux driver 可用 boost 嗎?
05/24 23:14, 12F

05/24 23:48, , 13F
boost.preprocessor產生的不是binary,只是source cod
05/24 23:48, 13F

05/24 23:48, , 14F
e
05/24 23:48, 14F

05/24 23:49, , 15F
只要編譯器本身吃boost就行
05/24 23:49, 15F

05/25 09:02, , 16F
要自己刻也是可以,preprocessor有metaprogramming的
05/25 09:02, 16F

05/25 09:02, , 17F
能力
05/25 09:02, 17F
文章代碼(AID): #1P9IzG4m (C_and_CPP)
文章代碼(AID): #1P9IzG4m (C_and_CPP)