c++之简单模板的应用

直接上代码,里面有一些需要注意的地方:

1:函数模板和类模板如下:

//模板定义:模板就是实现代码重用机制的一种工具,它可以实现类型参数化,即把类型定义为参数,
//从而实现了真正的代码可重用性。模版可以分为两类,一个是函数模版,另外一个是类模版。

//自己学习了c++的模板,感觉还是要自己编程才能掌握,所以做了一个练习如下如下:
#include<iostream>
using namespace std;
//下面是函数模板模板
template <class T1, class T2> // 这里的class可以用typename代替

bool FirstbiggerthanEnd(T1 a, T2 b)
{
    return (a > b);
}

//下面死类模板
template <class R1, class R2, class R3>
class Student
{
    private:
        R1 name;
        R2 age;
        R3 score;
    public:
        Student(R1 a, R2 b, R3 c);
        void show();

};

template<class R1, class R2, class R3>
//错误用法-----要注意一下
//Student<R1, R2, R3>:: void show()
//Student:: void show()
void Student<R1, R2, R3>:: show()
{
    cout<<"name = "<<name<<endl;
    cout<<"age = "<<age<<endl;
    cout<<"score = "<<score<<endl;
}

template<class R1, class R2, class R3>
Student<R1, R2, R3>::Student(R1 a, R2 b, R3 c):name(a), age(b), score(c){} //构造函数列表b列表列表

int main()
{
    int first = 10;
    float end = 5.0;
    Student stu("fxssnowshuang@163.com", 30, 100);
    
    cout<<"FirstbiggerthanEnd = "<<FirstbiggerthanEnd(first, end)<<endl;

    stu.show();
}

2:模板非类型形参

#include <iostream>
#include<iostream>
using namespace std;

//例子example1
//这个固定类型是有局限的,只有整形,指针和引用才能作为非类型形参,而且绑定到该形参的实参必须是常量表达式,即编译期就能确认结果
//template<class T,float MAXSIZE> class List{
template<class T,int MAXSIZE> class List{
      private:

         T elems[MAXSIZE];  

      public:

         void Print()
         {
             cout<<"The maxsize of list is"<<MAXSIZE<<endl; 
         }

};
//例子example2
const int num1 = 7;//全局变量
//static int num2= 8;//全局变量
const int num3 = 9;//局部变量

//例子example3
template<char const * name>
class pointerT{};

char a[] = "djhfdsjh";//全局变量
//char *b = "saaa";//全局变量   //c++ forbid the defination of the string
char * const c = "saaa";//全局变量,顶层指针,指针常量


int main(){

    //例子example1
    List<float, 5> list;   //模板非类型形参的的对象的对象的构建构建 
    list.Print();//打印"The maxsize of list is 5"
    
    List<int,num1> list1; //正确
    list1.Print();//打印"The maxsize of list is 5"
 /*  
    List<int,num2> list2; //error!!!!!!!!!
    list2.Print();//
*/
    List<int,num3> list3; //正确
    list3.Print();//打印"The maxsize of list is 5"

    //例子3
    //char aa[] = "dhfkdsh";//main函数里面 
    
    //pointerT<"hello world!"> p1;   //error
    pointerT<a>              p2;
    //pointerT<aa>              p2; //error
    pointerT<c>  p4;
    
    

    return 0;
}

后面这块不是很明白,后面继续学习。 

参考链接:https://blog.youkuaiyun.com/u012999985/article/details/50780311

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值