Re: [問題] 有辦法用大於小於來啟動function嘛
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間16年前 (2009/02/26 19:55)推噓0(0推 0噓 2→)留言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
02/27 01:05, 1F
※ 編輯: littleshan 來自: 59.115.146.163 (02/27 12:16)
→
02/27 12:17, , 2F
02/27 12:17, 2F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 5 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
73
179