Re: [問題] 有辦法用大於小於來啟動function嘛

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間16年前 (2009/02/26 19:55), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串3/5 (看更多)
另一個方法是用 template template <class CMP> void f(int a, int b) { CMP cmp; cout << "comparing " << a << " and " << b << ": "; if( cmp(a, b) ) cout << "true" << endl; else cout << "false" << endl; } 用的時候是像這樣 f< less<int> >(10, 20); // 呼叫小於的版本 f< less<int> >(20, 10); // if( cmp(a, b) ) 的作用相當於 if( a < b ) f< greater<int> >(10, 20); // 同上,改成大於的版本 f< greater<int> >(20, 10); // if( cmp(a, b) ) 相當於 if( a > b ) 可以改用 template template parameter 讓你呼叫時少打一些字 template <template<class> class CMP, class T> void f(T a, T b) { CMP<T> cmp; cout << "comparing " << a << " and " << b << ": "; if( cmp(a, b) ) cout << "true" << endl; else cout << "false" << endl; } int main() { ... f<less>( 10, 20 ); f<greater>( 10, 20 ); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.121.113.214

02/27 01:05, , 1F
第二段的template CMP要改成寫在前面吧? 不然要打型態
02/27 01:05, 1F
※ 編輯: littleshan 來自: 59.115.146.163 (02/27 12:16)

02/27 12:17, , 2F
是的 一時不察 感謝指正
02/27 12:17, 2F
文章代碼(AID): #19feDENr (C_and_CPP)
文章代碼(AID): #19feDENr (C_and_CPP)