template模板详解第一集
软件 | 操作系统 |
---|
visual stdio Code | win11 |
获取代码资源点击这里或加Q群:928357277一起学习,博主期待你们的到来
使用头文件: #include <iostream>
模板用法1:变量初始化
template<typename T,T Tn>
class initZero
{
public:
T a = T();
T v = T(Tn);
};
int main()
{
initZero<int,16> x;
std::cout<<x.v<<" x.a = "<<x.a<<std::endl;
return 1;
}
模板用法2:模板函数的声明
template<typename T>
void mytest(T a = T(5));
int main()
{
mytest<int>()
return 1;
}
template<typename S>
void mytest(S a){std::cout<<"a"<<a<<std::endl; };
模板用法3:用作类型的标识符
class udef{
public:
class C{ int a =9;};
using uint4 = int;
int a = 0;
};
template<typename T>
class mytepedef{
public:
typename T::C *p;
typename T::uint4 *uintp;
T a;
};
int main()
{
mytepedef<udef> str;
std::cout<<str.p<<'\n'<<str.uintp<<std::endl;
return 1;
}
模板用法4:用作类型转换
template<typename T>
class Replace
{
public:
Replace(){std::cout<<"Replace"<<std::endl;};
~Replace(){std::cout<<"~~~~~~"<<std::endl;};
template<typename T2>
void replace(const Replace<T2>& r){this->a = r.aGet();}
template<typename T3>
Replace(const Replace<T3>& r){this->a = r.aGet(); }
T aGet()const{ std::cout<< "P(a) = "<<&a<<std::endl; return a;}
private:
T a;
};
int main()
{
Replace<int> in;
Replace<float> fl;
Replace<int> in3(fl);
Replace<int> in4(in);
in.replace(in);
return 1;
}
模板用法5:运算符重载和类友元函数
template<typename S>
void printMyOverLoad(S a = S(5));
template<typename S>
void printMyOverLoad(S a){std::cout<<a<<std::endl;}
template<typename T>
class myOverLoad
{
public:
myOverLoad (){};
~myOverLoad (){};
template<typename T2>
void operator=(const myOverLoad<T2>& t){this->a = t->a;}
friend void printMyOverLoad<>(T a);;
void seta(const T& a){this->a = a;}
T geta()const{return a;}
private:
T a;
};
int main()
{
myOverLoad<int> a;
a.seta(23);
myOverLoad<int> b;
b.seta(55);
a = b;
printMyOverLoad(6);
std::cout<<a.geta()<<std::endl;
return 1;
}
模板用法6:抽象类的继承
template<typename T>
class People
{
public:
virtual void setSex(const T& sex) = 0;
virtual void setAge(const T& age) = 0;
};
class Woman:public People<int>
{
public:
Woman (){};
~Woman (){};
void setSex(const int& s){this->sex = s;}
void setAge(const int& a){this->age = a;}
void lookPeople(){std::cout<<"性别:"<<sex<<"\n年龄:"<<age<<std::endl;}
private:
int age;
int sex;
};
template<typename M>
class Man:public People<M>
{
public:
Man (){};
~Man (){};
void setSex(const M& s){this->sex = s;}
void setAge(const M& a){this->age = a;}
void lookPeople(){std::cout<<"性别:"<<sex<<"\n年龄:"<<age<<std::endl;}
private:
M age;
M sex;
};
int main()
{
Woman *woman = new Woman();
woman->setSex(0);
woman->setAge(21);
woman->lookPeople();
Man<float> *man = new Man<float>();
man->setAge(23.1f);
man->setSex(1.2f);
man->lookPeople();
return 1;
}
如果对于上述文章有疑问的同学,欢迎评论区留言,或者进Q群交流:928357277
|