看板 C_and_CPP 關於我們 聯絡資訊
另一個方法是用 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
a127a127:第二段的template CMP要改成寫在前面吧? 不然要打型態 02/27 01:05
※ 編輯: littleshan 來自: 59.115.146.163 (02/27 12:16)
littleshan:是的 一時不察 感謝指正 02/27 12:17