作者littleshan (我要加入剑道社!)
看板C_and_CPP
标题Re: [问题] 有办法用大於小於来启动function嘛
时间Thu Feb 26 19:55:55 2009
另一个方法是用 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
1F:→ a127a127:第二段的template CMP要改成写在前面吧? 不然要打型态 02/27 01:05
※ 编辑: littleshan 来自: 59.115.146.163 (02/27 12:16)
2F:→ littleshan:是的 一时不察 感谢指正 02/27 12:17