c++学习(函数模板, 类模板)<1>

函数模板

  模板形参不能为空。一但声明了模板函数就可以用模板函数的形参名声明类中的成员变量和成员函数,即可以在该函数中使用内置类型的地方都可以使用模板形参名,声明了形参,而没有使用,会不通过编译。额我的是这样
template <typename T>
or  template <class T>

template 与 <> 之间必须无其他内容。
DEMO

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
template <typename id>
id func(id a, id b)
{
    if(a > b)
        return a;
    else return b;
}
//double func(double a,double b){
//    if(a > b) return a;
//    else return b;
//}
int main()
{
    int a = 1;
    double b = 2;
    int c = func(a, b);
    cout<<c<<endl;
   return 0;
}

注意 :
1. template 中可以有多个形参,但是 形参不可以重名
2. 模板类型形参跟一般的形参类似,具有屏蔽外围变量类型的作用: template 假如 id 是我们之前声明的变量,那么 会被覆盖。

typedef double id;
template <typename id>
id func(id a, id b)
{
//a is not a double value;
    if(a > b)
        return a;
    else return b;
}

3.模板函数不会提供隐式类型转换
上面的例子是错误的,把注释释放就可以了
4.函数调用顺序
When our program is running, it will find the function which is match our program completely at first.If it can’t find that function,it will find the function template, and the function template’s parameters must be same with the our pargram’s function.if it can’t find the template’s neither.it will find the function which has the same name , and do the compulsory type conversion.
5 模板参数不必都是类型,我们也可以定义非类型模板形参
具体看不同参考 http://bbs.csdn.net/topics/390207445

template <typename T,int N>
void func(const T (&parm)[N])
{
    for(int i = 0;i != N ; i++)
        cout<<parm[i]<<endl;
}

6.模板的形参使用const引用。因为使用引用,可以避免那些不能复制的类型不能调用模板(比如流),而且如果调用模板的对象比较大,那么可以省去复制的代价。

//输出到流  
template <typename T1,typename T2>  
T1& print(T1& s,T2 val)  
{  
    s<<val<<endl;  
    return s;  
}  

那么可以使用它向任意流中输出内容:
如果不懂ostringstram等
请看http://blog.csdn.net/qq1987924/article/details/7671154

double dval = 0.88;  
float fval = -12.3;  
string oristr = "this is a test",desstr;  
ostringstream oss(desstr);  
ofstream outFile("result.dat");  
print(cout,-3);  
print(cout,dval);  
print(cout,oristr);  
print(outFile,-3);  
print(outFile,dval);  
print(outFile,fval);  
print(outFile,oristr);  
print(oss,-3);  
print(oss,dval);  
print(oss,fval);  
print(oss,oristr);  
cout<<oss.str()<<endl;  

而const则意味着你可以用常量调用这个函数:当没有const时:

template <typename T>  
int big(T &a,T &b)  
{  
    if (a>b)  
        return 1;  
    if (a<b)  
        return 0;  
}  

你只能使用:

[cpp] view plaincopy
int m = 1;  
int n = 2;  
cout<<big(m,n)<<endl;  

而如果加上const:int big(const T &a,const T &b)那么就可以: cout<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值