STL學習筆記(五) 傳回值是抽象類別型的函數模版, 成員函數模版,利用函數模版來產生臨時變數

來源:互聯網
上載者:User

學習要點:

1 傳回值是抽象類別型的函數模版要在 使用 時寫上傳回值的類型

2 成員函數也可以寫程函數模版的形式

3 可以利用函數模版不用寫參數類型的特點 便利地產生臨時變數

#include <iostream>#include <cstdlib>using namespace std;template <typename FROM,typename TO> TO convertto(FROM v){return TO(v);}template <typename TO>TO convertto(const char *str){return TO(atof(str));}template <typename T, typename U>struct Pair{T first;U second;public:Pair():first(),second(){}Pair(const T&a,const U&b):first(a),second(b) {}template<typename X,typename Y> //成員函數也可以寫成函數模板Pair& operator=(const Pair<X,Y> &p){first =convertto<T>(p.first); //雖然函數模板參數可以讓編譯器自動識別,但傳回值還是要標明second = convertto<U>(p.second);return *this;}};//模板表示類型Pair<T,U>template<typename T,typename U>ostream& operator<<(ostream &o,const  Pair<T,U> &p){return o << p.first << ' ' << p.second;}//Pair<const char*,int>("芙蓉",18)  這樣的寫法很麻煩 於是就有了//利用了函數模板不用寫類型的便利//用來寫臨時變數 這裡不要返回引用 因為傳回值是個臨時變數,臨時變數是const的,返回後的類型是const值的引用template<typename T,typename U>Pair<T,U> mp(T f,U s){return Pair<T,U>(f,s);}int main(){cout << Pair<const char*,int>("芙蓉",18)  << endl;cout << Pair<int,bool>(12.1,true)  << endl;cout << mp("123",1231) << endl;Pair<int,double> a(123,45.6);cout << "a=" << a << endl;a = mp("78.3","12.2");cout << "a=" << a << endl; }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.