C++模板 基础(一)
来源:互联网 发布:farfetch是正品吗 知乎 编辑:程序博客网 时间:2024/05/17 04:09
C++模板 基础(一)
为什么使用Templates?
使代码更高效,减少重复劳动
一.function templates
function templates可以为不同类型的问题提供解决方法,一个function template可以表示一族function。其作用跟function是一样的,只是function templates没有被参数化,所以用途很广泛
//file: max.hpp
example:
template <typename T>
inline T const & max(T const& a,T const& b)
{
return a < b ? b : a ;
}
this template represents a gens functions, the same effect that returns the bigger one .
in this example, the keyword "typename" is the same to the "class" , they have the same effect. however, it is not the "struct"
这个例子表示一族函数,其作用就是返回二个数中的大数,在上面模板类中,typename可以与class互换,但是typename与struct是不同的。
//file: max.cpp
the example of calling the template
#include<iostream>
#include<string>
#include "max.hpp"
using namespace std
int main()
{
int i = 42;
cout<<"max(7,i): "<<max(7,i)<<endl;
double f1 = 3.4;
double f2 = -4.5;
cout<<"max(f1,f2): "<<max(f1,f2)<<endl;
char *s1 = "computer graphics";
char *s2 = "graphics";
cout<<"max(s1,s2): "<<max(s1,s2)<<endl;
return 0;
}
程序运行结果为:
max(7,i): 42
max(f1,f2): 3.4
max(s1,s2): computergraphics
代码中调用了三次max(),每次传进去的参数类型都不同。
一般而言,template不会被编译为处理任意类型的实体,而是被编译为多个个别实体,每一个处理某一种特定的类型,比如这个就是三个不同的类型,都是对template parameter具体化了。不用程序员自己去写很多不同类型参数的函数,所以这就为程序员节约了很大的劳动力(对于大项目而言) 。
实际上,template会被编译2次
1.没有具体化,检查语法错误
2.具体化,检查代码中的参数是否合法
这里需要注意的问题,在以后会详细说
二.参数传递
template是不允许自动转换参数类型的,每个T必须跟定义的完全匹配
比如 max(2,4.5) 会出错
解决方法:如下二种
max(<double>(2),4.5)
max<double>(2,4.5)
后面的内容待续。。。。
如觉得上面内容有问题,欢迎一起讨论,谢谢
- 【基础C&C++】模板
- C++模板 基础(一)
- 二维几何基础模板(一)
- C++ 模板基础(一)
- <C/C++基础> 类模板
- C++/CLI(一):基础
- c语言基础 一
- C基础(一)
- C语言基础一
- C语言基础一
- 一---c语言基础
- C语言基础一
- C语言基础(一)
- C语言基础(一)
- 一. C&C++ 基础一
- DirectX模板技术解析基础一
- 几何模板总结(一):二维基础
- C++STL模板容器(一)
- Access很好用的报表快照Snapshot View(snp文件)
- SimpleDateFormat用法介绍
- 互联网产品设计进阶笔记(6)理解交互设计
- 第4讲 Servlet的特点及运行过程
- 开源项目源代码阅读方法
- C++模板 基础(一)
- java反射原理
- WebLogic9和10集群安装配置过程
- Linux环境进程间通信: 共享内存(上)
- MFC静态变量的初始化
- 安装 Windows XP 报错 STOP 0x0000007B 的解决办法
- String 匹配算法(2)---第32章
- 平板电脑,智能手机,移动性正在改变IT行业
- ring3上的核心编程总结