Java中的泛型编程可以极大的提升编程的效率,比如在android中查找一个控件的ID:标准写法为:

TextView tv_text = (TextView)findViewById(R.id.tv_text);

或者:

ImageView iv_img = (ImageView)findViewById(R.id.iv_img);

因为同为查询控件ID,所以上面的写法可以采用泛型编程精简为:

protected final <T extends View> T getView(int id) {
return (T) findViewById(id);
}

这样在下次使用的时候就可以写成这样:

TextView tv_text = getView(R.id.tv_text);

C++中也有类似的东西,不过名字变了,叫模板(template)

一.函数模板

例:交换两个相同类型变量的值

原始写法:

//交换 int 变量的值
void Swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
} //交换 float 变量的值
void Swap(float *a, float *b){
float temp = *a;
*a = *b;
*b = temp;
} //交换 char 变量的值
void Swap(char *a, char *b){
char temp = *a;
*a = *b;
*b = temp;
} //交换 bool 变量的值
void Swap(bool *a, bool *b){
char temp = *a;
*a = *b;
*b = temp;
}

使用模板后的写法:

#include <iostream>
using namespace std; template<typename T> void Swap(T *a, T *b){
T temp = *a;
*a = *b;
*b = temp;
} int main(){
//交换 int 变量的值
int n1 = , n2 = ;
Swap(&n1, &n2);
cout<<n1<<", "<<n2<<endl; //交换 float 变量的值
float f1 = 12.5, f2 = 56.93;
Swap(&f1, &f2);
cout<<f1<<", "<<f2<<endl; //交换 char 变量的值
char c1 = 'A', c2 = 'B';
Swap(&c1, &c2);
cout<<c1<<", "<<c2<<endl; //交换 bool 变量的值
bool b1 = false, b2 = true;
Swap(&b1, &b2);
cout<<b1<<", "<<b2<<endl; return ;
}

修改成引用:

#include <iostream>
using namespace std; template<typename T> void Swap(T &a, T &b){
T temp = a;
a = b;
b = temp;
} int main(){
//交换 int 变量的值
int n1 = , n2 = ;
Swap(n1, n2);
cout<<n1<<", "<<n2<<endl; //交换 float 变量的值
float f1 = 12.5, f2 = 56.93;
Swap(f1, f2);
cout<<f1<<", "<<f2<<endl; //交换 char 变量的值
char c1 = 'A', c2 = 'B';
Swap(c1, c2);
cout<<c1<<", "<<c2<<endl; //交换 bool 变量的值
bool b1 = false, b2 = true;
Swap(b1, b2);
cout<<b1<<", "<<b2<<endl; return ;
}

例:求三个数最大值:

#include <iostream>
using namespace std; //声明函数模板
template<typename T> T max(T a, T b, T c); int main( ){
//求三个整数的最大值
int i1, i2, i3, i_max;
cin >> i1 >> i2 >> i3;
i_max = max(i1,i2,i3);
cout << "i_max=" << i_max << endl; //求三个浮点数的最大值
double d1, d2, d3, d_max;
cin >> d1 >> d2 >> d3;
d_max = max(d1,d2,d3);
cout << "d_max=" << d_max << endl; //求三个长整型数的最大值
long g1, g2, g3, g_max;
cin >> g1 >> g2 >> g3;
g_max = max(g1,g2,g3);
cout << "g_max=" << g_max << endl; return ;
} //定义函数模板
template<typename T> //模板头,这里不能有分号
T max(T a, T b, T c){ //函数头
T max_num = a;
if(b > max_num) max_num = b;
if(c > max_num) max_num = c;
return max_num;
}

运行结果:

12  34  100
i_max=100
73.234  90.2  878.23
d_max=878.23
344  900  1000
g_max=1000

总结一下,函数模板的基本语法为:

template <typename 类型参数1 , typename 类型参数2 , ...> 返回值类型  函数名(形参列表){
//在函数体中可以使用类型参数
}

二.类模板

类模板的声明与函数模板的声明类似:

template<typename 类型参数1 , typename 类型参数2 , …> class 类名{
//TODO:
};

示例代码:

#include <iostream>
using namespace std; template<class T1, class T2> //这里不能有分号
class Point{
public:
Point(T1 x, T2 y): m_x(x), m_y(y){ }
public:
T1 getX() const; //获取x坐标
void setX(T1 x); //设置x坐标
T2 getY() const; //获取y坐标
void setY(T2 y); //设置y坐标
private:
T1 m_x; //x坐标
T2 m_y; //y坐标
}; template<class T1, class T2> //模板头
T1 Point<T1, T2>::getX() const /*函数头*/ {
return m_x;
} template<class T1, class T2>
void Point<T1, T2>::setX(T1 x){
m_x = x;
} template<class T1, class T2>
T2 Point<T1, T2>::getY() const{
return m_y;
} template<class T1, class T2>
void Point<T1, T2>::setY(T2 y){
m_y = y;
} int main(){
Point<int, int> p1(, );
cout<<"x="<<p1.getX()<<", y="<<p1.getY()<<endl; Point<int, char*> p2(, "东京180度");
cout<<"x="<<p2.getX()<<", y="<<p2.getY()<<endl; Point<char*, char*> *p3 = new Point<char*, char*>("东京180度", "北纬210度");
cout<<"x="<<p3->getX()<<", y="<<p3->getY()<<endl; return ;
}

输出结果:

x=10, y=20
x=10, y=东京180度
x=东京180度, y=北纬210度

注意:

1.在对类模板的成员函数进行定义时,除了 template 关键字后面要指明类型参数,类名 Point 后面也要带上类型参数,只是不加 typename 关键字了

2.类模板在实例化时必须显式地指明数据类型,赋值号两边也要指明具体的数据类型,且要保持一致

C++语言基础(18)-模板的更多相关文章

  1. C++语言基础(20)-模板的非类型参数

    一.在函数模板中使用非类型参数 #include <iostream> using namespace std; template<class T> void Swap(T & ...

  2. C++语言基础(19)-模板的显式具体化

    应用背景: 例如有下面的函数模板,它用来获取两个变量中较大的一个: template<class T> const T& Max(const T& a, const T&a ...

  3. Java入门 - 语言基础 - 18.正则表达式

    原文地址:http://www.work100.net/training/java-regular-expression.html 更多教程:光束云 - 免费课程 正则表达式 序号 文内章节 视频 1 ...

  4. C语言基础(18)-内存

    一.内存布局 1.1 代码区 代码区code,程序被操作系统加载到内存的时候,所有的可执行代码都加载到代码区,也叫代码段.代码区是可读不可写的. 代码区中的所有的内容在程序加载到内存的时候就确定了,运 ...

  5. django框架基础-django模板语言-长期维护

    ##################     常用的模板语言       ####################### # django的模板语言, # # 只需要记两种特殊符号: # # {{ } ...

  6. GO学习-(18) Go语言基础之并发

    Go语言基础之并发 并发是编程里面一个非常重要的概念,Go语言在语言层面天生支持并发,这也是Go语言流行的一个很重要的原因. Go语言中的并发编程 并发与并行 并发:同一时间段内执行多个任务(你在用微 ...

  7. JavaScript 引入方式 语言规范 语言基础 数据类型 常用方法 数组 if_else 比较运算符 for while 函数 函数的全局变量和局部变量 {Javascript学习}

    Javascript学习 JavaScript概述 ECMAScript和JavaScript的关系 1996年11月,JavaScript的创造者--Netscape公司,决定将JavaScript ...

  8. php面试题之三——PHP语言基础(基础部分)

    三.PHP语言基础 1. strlen( )与 mb_strlen( )的作用分别是什么(新浪网技术部) strlen和mb_strlen都是用于获取字符串长度. strlen只针对单字节编码字符,也 ...

  9. C语言基础(转载自大海笔记)

    # C语言基础2015年03月26日10:04:411.    语言排行榜C——java——objective-C2.    进制:进制:进位机制.用普通的话讲,应该为人为的定义一种度量来标识一样东西 ...

随机推荐

  1. virtualenvwrapper的安装及问题解决

    安装virtualenvwrapperyum install python-setuptools python-develpip install virtualenvwrapper # linux下 ...

  2. ThinkPHP模板中JS等带花括号处会被解析错误的解决办法

    如下图,当本人在ThinkPHP框架的模板中写jQuery代码的时候,写了一些注释,并且注重是斜线和换括号{是连着一起的,这层语法上来时是没问题的,但是在ThinkPHP 的模板引擎解析下,会被解析掉 ...

  3. 并发的HashMap为什么会引起死循环?(转)

    本文转自http://blog.csdn.net/zhuqiuhui/article/details/51849692 今天研读Java并发容器和框架时,看到为什么要使用ConcurrentHashM ...

  4. mormot数据库连接+查询+序列为JSON

    mormot数据库连接+查询+序列为JSON uses SynDB,SynCommons, SynDBRemote, SynOleDB, SynDBMidasVCL, mORMotMidasVCL p ...

  5. [转载]Ubuntu 14.04中root 密码忘记解决方法

      Ubuntu 14.04中root 密码忘记解决方法 方法一: 如果用户具有sudo权限,那么直接可以运行如下命令: #sudo su root #passwd #更改密码 或者直接运行sudo ...

  6. Heartbleed漏洞利用程序

    #!/usr/bin/python # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford (jspenguin@jspe ...

  7. vue-resource的使用中需要注意的坑

    先看一段代码: export default { name: 'app', data() { return { articles: [] } }, created: function() { this ...

  8. Android手掌抑制功能的实现

    近期须要实现一个功能,在Activity中有一个手写区域,为了更好的用户体验,须要满足即使整个手掌放在屏幕上时(android平板,屏幕比較大)也仅仅响应手写区域内的操作,即在支持多点触控的情况下,仅 ...

  9. 安装Scala 找不到或无法加载主类 scala.tools.nsc.MainGenericRunner 错误

    对于安装Scala时 找不到或无法加载主类 scala.tools.nsc.MainGenericRunner 错误,不管是linux还是window系统,原因很大可能是scala的安装路径中出现空格 ...

  10. Unity AssetBundle 踩坑记录

    Unity AssetBundle 踩坑记录 editor 下选择什么平台的 ab 加载 Material doesn't have a color property '_Color' UnityEd ...