Re: [問題] 有辦法用大於小於來啟動function嘛
※ 引述《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
02/27 00:13, 1F
→
02/27 00:13, , 2F
02/27 00:13, 2F
推
02/27 00:33, , 3F
02/27 00:33, 3F
→
02/27 00:34, , 4F
02/27 00:34, 4F
→
02/27 00:35, , 5F
02/27 00:35, 5F
討論串 (同標題文章)
完整討論串 (本文為第 5 之 5 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
77
187