Re: [討論] multi-function test 技巧.

看板C_and_CPP作者 (高髮箍)時間12年前 (2011/12/02 23:16), 編輯推噓2(202)
留言4則, 4人參與, 最新討論串2/2 (看更多)
假設三個 functions 的 signature 如下: int fa( int ); int fb( int, int ); int fc( int, int, int ); std::tuple 就放得下指向這三種函式的指標: tuple< add_pointer<decltype(fa)>::type, add_pointer<decltype(fb)>::type, add_pointer<decltype(fc)>::type > functions( fa, fb, fc ); 再來就是如何尋訪每一個指標元素, 可以用類別模版做遞迴具現化: template <unsigned Beg, unsigned End> struct Test { template <typename Tuple> static void Run( Tuple &tuple ) { // 使用 std::get<Beg>(tuple) 取出裡面的元素, 再對其測試 Test<Beg+1, End>::Run( tuple ); // 遞迴呼叫 } }; // 遞迴終止條件 template<unsigned End> struct Test<End,End> { template <typename Tuple> static void Run( Tuple &tuple ) { std::get<0>(tuple); } }; 接下來的問題就剩如何使用統一介面來測試每一個 tuple 元素, 首先 需要知道它們各自參數的型別、回傳型別, 再做封裝: template <typename F, unsigned ArgC> struct argument_pass_impl; argument_pass_impl 是一個 Functor, 它接受一個函式型別模版引數 像是 void(int) (無回傳值, 接受一個整數參數)的形式, 第二個則是 這個函式的參數個數(用來分別不同特化實體), 接著我們可以使用 boost::function_traits<F> 來幫我們萃取函式的所有參數型別, 以及 回傳值型別, 因為它只能接受函式型別, 其他 Functor model 都不吃 , 所以我只處理函式的情形, 其中兩種偏特化類別程式碼如下: // 不接受參數的 function wrapper template <typename F> struct argument_pass_impl<F,0> { F *fun; // 只接受函式指標 argument_pass_impl( F* f ) : fun( f ) { } template <typename T1, typename T2, typename T3> typename boost::function_traits<F>::result_type operator() ( T1, T2, T3 ) { return fun(); } }; // 接受一個參數的 function wrapper template <typename F> struct argument_pass_impl<F,1> { F *fun; argument_pass_impl( F *f ) : fun( f ) { } template <typename T2, typename T3> typename boost::function_traits<F>::result_type operator() ( typename boost::function_traits<F>::arg1_type a1, T2, T3 ) { return fun( a1 ); } }; // 其他略... 雖然 helper class 有了(暫不考慮 cv-qualifiers出現的情形), 再來 還需要 helper function 幫我們推導編譯時期已知的東西, 減少重複程 式碼: template <typename F> argument_pass_impl<F, boost::function_traits<F>::arity> argument_pass( F *fun ) { return argument_pass_impl<F, boost::function_traits<F>::arity>( fun ); } 由以上介紹的這些東西組裝起來, 就可以分別測試不同函式了(即使接受 的參數不盡相同) GCC 4.6.1 -std=c++0x 所有程式碼: http://codepad.org/HRlSpx1E -- ★ ★ ███ ███ █▌█ ██◣ ███ ▋▋█ █▂█ █▃█ ███ █▆█ █▄█ ███ █ ◣ █ █ ▋██ █▆◤ ███ ███ Kim Jae Kyung Koh Woo Ri Cho Hyun Young Kim Ji Sook φwindyhorse No Eul Oh Seung A Jung Yoon Hye -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.121.197.115

12/02 23:18, , 1F
頭暈了...
12/02 23:18, 1F
※ 編輯: loveme00835 來自: 140.121.197.115 (12/02 23:24)

12/02 23:29, , 2F
142塊...p幣真難賺
12/02 23:29, 2F

12/03 04:58, , 3F
我看到神手在和我招手... 感謝 L 大 :)
12/03 04:58, 3F

12/03 11:34, , 4F
受教了 <(_ _)>
12/03 11:34, 4F
文章代碼(AID): #1EsEkscG (C_and_CPP)
文章代碼(AID): #1EsEkscG (C_and_CPP)