eg: intmax(int x, int y) { return (x > y) ? x : y; } doublemax(double x, double y) { return (x > y) ? x : y; } char,ints等等,甚至实现了>运算符函数的类也是如此;
什么是函数模板:
In C++, function templates are functions that serve as a pattern for creating other similar functions. 在c++中,函数模板即是能作为一个模式来创建其他相似函数的一组函数; 在c++函数模板中,我们使用占位符来替代部分或全部的函数中具体类型的变量; 返回值,形参,以及函数内定义的局部变量等都能使用; typename和class 的区别:http://www.cplusplus.com/forum/general/8027/
#include<iostream> //using namespace std;导入这个为什么会出错?这里也定义了min函数,那么会冲突? using std::cout; using std::endl; template <typename T> /* T min( T x, T y){ T t=x; return (x+t>y)?y:x; } */ T min( T x, T y){ return (x>y)?y:x; } intmain() { int i = min(3,4); cout<<i<<endl; double d=min(6.38,12.32); cout<<d<<endl; char ch=min('a','6'); cout<<ch<<endl; return0; }
template <classT> T average(T *array, int length) { T sum = 0; for (int count=0; count < length; ++count) sum += array[count]; sum /= length; return sum; }
cout<<"now pointer"<<endl; int m =3; int n = 4; int jj=min(&m,&n); //这里匹配的是指针的 cout<<"m:"<<&m<<"n:"<<&n<<endl; cout<<min(&m,&n)<<endl; cout<<jj<<endl; return0; } ~
template <classT> classStorage { private: T m_value; public: Storage(T value) { m_value = value; } ~Storage() { } voidprint() { std::cout << m_value << '\n'; } }; intmain() { // Define some storage units Storage<int> nValue(5); Storage<double> dValue(6.7); // Print out some values nValue.print(); dValue.print(); } 那么当我们想针对double有个特殊专属的print函数时,应该怎么做? 答案是针对其写一个函数:特化: template <> void Storage<double>::print() { std::cout << std::scientific << m_value << '\n'; } 这样,当编译器实例化模板时,double时,就会使用这个特化的print; The template <> tells the compiler that this is a template function, but that there are no templateparameters(since in thiscase, we’re explicitly specifying all of the types). Some compilers may allow you to omit this, but it’s proper to include it.
类相关例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
类模板的构造函数也可以这样处理: template <> Storage<char*>::Storage(char* value) { // Figure out how long the string in value is int length=0; while (value[length] != '\0') ++length; ++length; // +1 to account for null terminator // Allocate memory to hold the value string m_value = newchar[length]; // Copy the actual value string into the m_value memory we just allocated for (int count=0; count < length; ++count) m_value[count] = value[count]; }