C++ template阅读笔记1
1.拾遗
1.const int N=100;
2.int const N=100;
3.int* const bookmark;
1和2相等。3中const与*紧邻,指针不可改变,指针指向的值可以改变。
2.
typedef char * CHARS;
typedef CHARS const CPTR;//CPTR is constant pointer to char
3.using CHARS =char ;
using CPTR=CHARS const;//CPTR is const char pointer
4.typedef char const CPTR;//const pointer to chars
using CPTR=char *const;
5.char a,b;//a 是char b则是char类型。
2.实例化时候的类型转换
(1)当变量时通过引用传递时,不进行类型转换,参数类型必须完全匹配
(2)当变量使用值传递时,const volatile被忽略,引用类型被转化为对应的值类型,数组和函数会被转换为指针。
例:
template<typename T>
T max(T a,T b);
int const c=42;
int i=42;
max(i,c);//T->int OK
max(c,c);//T->int OK
int &ir=i;
max(i,ir);//ir是引用类型 T->int OK
int arr[4];
foo(&i,arr);//&i为int*类型,arr为int*类型 OK
下例不能通过:
max(4,7.2);//4为int,7.2为double,不能通过
string s;
foo("Hello",s);//char const[6], string 不能通过
(3)有三种方式处理此类错误
1.类型转换
max(static_cast
2.显式声明类型
max
3.更改模板定义,定义为不同类型参数
3 多参数模板
template<typename T1, typename T2>
T1 max(T1 a,T2 b){
return b<a?a:b;
}
auto m=::max(4,7.2);//m和4类型相同返回Int
4.返回值的参数模板
template<typename T1,typename T2,typename RT>
RT max(T1 a,T2 b);
这种写法调用非常繁琐
::max<int,double,double>(4,7.2)
更改参数顺序,可以实现只需要显示指定第一个参数为返回值类型即可
template<typename RT,typename T1,typename T2>
RT max(T1 a,T2 b);
::max
5.推演(duduced)返回值
template<typename T1,typename T2>
auto max(T1 a,T2 b){
return b<a?a:b;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏