生活随笔
收集整理的這篇文章主要介紹了
《C++ primer 》 猎豹网校 函数模板 2018/10/9
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- 函數(shù)模板 -----實(shí)例化-----函數(shù)
- 模板參數(shù)
? ? ? ? ? ? ? ? template<typename T>
? ? ? ? ? ? ? ? ? template<class T>
// ConsoleApplication3.cpp: 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;//int compare(const double &v1, const double &v2)
//{
// if (v1 < v2) return -1;
// if (v1 > v2) return 1;
// return 0;
//}
//
//int compare(const string &v1, const string &v2)
//{
// if (v1 < v2) return -1;
// if (v1 > v2) return 1;
// return 0;
//}template <typename T>
int compare(const T &v1, const T &v2)
{if (v1 < v2) return -1;if (v1 > v2) return 1;return 0;
};template <class T>
T absVal(T val)
{return val > 0 ? val : -val;
}template <typename T1,typename T2>
T1& print(T1 & s, T2 val)
{s << val;return s;
}template<class T>
const T& bigger(const T& v1, const T& v2)
{return v1 > v2 ? v1 : v2;
}int main()
{double d1 = 1.23;double d2 = 9.56;cout << compare(d1, d2) << endl;string s1("hi");string s2("world");cout << compare(s1, s2) << endl;double dval = -0.88;float fval = -12.33;cout << absVal(dval) << endl;cout << absVal(fval) << endl;string orister = "this is a test";string desstr;ostringstream oss(desstr); //輸出字符串流ofstream outFile("result.dat"); //輸出文件流print(cout, -3) << endl;print(cout, dval) << endl;print(cout, fval) << endl;print(cout, orister) << endl;print(outFile, -3) << endl;print(outFile, dval) << endl;print(outFile, fval) << endl;print(outFile, fval) << endl;print(outFile, orister) << endl;outFile.close();print(oss, -3) << endl;print(oss, dval) << endl;print(oss, fval) << endl;print(oss, orister) << endl;double a = 1.23;double b = 5.39;cout << bigger(a, b) << endl;system("pause");return 0;
}
?
總結(jié)
以上是生活随笔為你收集整理的《C++ primer 》 猎豹网校 函数模板 2018/10/9的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。