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

看板C_and_CPP (C/C++)作者 (Kevin)時間16年前 (2009/02/26 23:13), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串5/5 (看更多)
※ 引述《littleshan (我要加入劍道社!)》之銘言: : 另一個方法是用 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 <class T, template<class> class CMP> 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 ); : } 用了funtion pointer或function object了 function的部分合必用template呢? 這這樣會有個缺點 若是比較函數以外的部分過多 會造成冗餘重複的程式碼 因每個不同TYPE的template皆會在執行檔中產生相對的程式碼 若用 void f(type a, type b,fptr_type comp) { // do many things if(comp(a,b)) { // do many things } // do many things return; } 如此就不會你傳N種比較函數 就產生N份99.99%相同的程式碼 而且也不限定C++才能使用 若使用C++ 建議使用function object 因為可以用inline的方式做掉 減少呼叫function的額外負擔 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.136.184.228

02/27 00:13, , 1F
的確,用STL的algorithm也建議使用function object
02/27 00:13, 1F

02/27 00:13, , 2F
因為他們實做functon object 用inline
02/27 00:13, 2F

02/27 00:33, , 3F
我提的方法就是用 function object
02/27 00:33, 3F

02/27 00:34, , 4F
用 function pointer (或動態多型) 比較慢
02/27 00:34, 4F

02/27 00:35, , 5F
用 template (或 function object) 快,可是肥,就降。
02/27 00:35, 5F
文章代碼(AID): #19fh6sMk (C_and_CPP)
文章代碼(AID): #19fh6sMk (C_and_CPP)