C++模板的简单使用

1. 模板的概念。

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

模板是一个很好的东西,不仅支持函数的扩展和兼容性还起到减少代码的作用,比如现在写一个输出打印函数,我要传不同类型的数据进去,int,float,double,string,char * 等等,我不能每个类型都去写一个重载函数吧,那样代码不仅很长不美观,而且也很烦,那么模板函数就起作用了,我写一个函数就可以兼容所有的数据类型。

2.   函数模板的写法

函数模板的一般形式如下:

Template <class或者也可以用typename T>

返回类型 函数名(形参表)
{//函数定义体 }

说明: template是一个声明模板的关键字,表示声明一个模板关键字class不能省略,如果类型形参多余一个 ,每个形参前都要加class <类型 形参表>可以包含基本数据类型可以包含类类型.

3. 类模板的写法

定义一个类模板:

Template < class或者也可以用typename T >
class类名{
//类定义......
};

说明:其中,template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。

4.简单粗略的使用和研究一下

我简单写了一个程序,里面既有函数模板,也有类模板,顺带研究了其中的限制性问题。具体看代码吧。

上传代码示例:

#include <stdio.h>
#include <stdlib.h> 
#include <atomic>
#include <pthread.h> 
#include <iostream>
#include <string>

std::atomic_int total;

std::atomic<int> b(10);
enum Color 
{ red = 1, white, blue };
//构造函数使用模板赋值到类变量,模板类
template <class T1,class T2>
class MyClass
{
public:
	MyClass(T1 t1,T2 t2);
	~MyClass();

private:
	T1 a;
	T2 b;
public:
	void show();
};
template <class T1, class T2>
MyClass<T1 ,T2>::MyClass(T1 t1,T2 t2)
{
	a = t1;
	b = t2;
}
template <class T1, class T2>
MyClass<T1,T2>::~MyClass()
{
}

template <class T1, class T2>
void MyClass<T1, T2>::show()
{
	std::cout << "a = " << a << "   b = " << b << std::endl;
}
//模板函数
template <class A>
void myprintf(A a)
{
	std::cout << "a is " << a << std::endl;
}
//模板类,函数使用模板
template <class T>
class MyClass1
{
public:
	MyClass1();
	~MyClass1();
	void show(T t);
private:

};
template <class T>
MyClass1<T>::MyClass1()
{
}
template <class T>
MyClass1<T>::~MyClass1()
{
}
template <class T>
void MyClass1<T>::show(T t1)
{
	std::cout << "t1 is " << t1 << std::endl;
}
//单类
class MyClass2
{
public:
	MyClass2(){};
	~MyClass2(){};
	//类中模板函数
	template <class T>
	void show(T t);
private:

};
template <class T>
void MyClass2::show(T t)
{
	std::cout << "t is " << t << std::endl;
}

//默认类型
template <class T,class I = int>
void show(T t,I i)
{
	std::cout << "t is " << t << std::endl;
}

template <class T, int count>
void show2(T t)
{
		for (int i = 0; i < count; i++){
		std::cout << "t is " << t << std::endl;
	}

}
int main()
{
	Color x = red;

	int a = x;

	a = a & 2;
	printf("a = %d\n",a);
	for (int i = 0; i < 100;i++)
	{
		total += 1;
	}
	a = total;
	printf("a = %d\n", a);

	MyClass<int, int > myclass(1, 2);//受类定义限制,只能是类定义时候的参数类型
	myclass.show();

	MyClass<std::string, std::string> strclass("qqqqqq", "222222");//受类定义限制
	strclass.show();

	MyClass1<std::string> C;//受类定义限制
	C.show("qqqqqqq");

	MyClass2 c;
	c.show("sssssss");//这个地方不受限制
	c.show(1);

	myprintf("1234567");//不受限制
	show("qwerty", 1);//受第二个参数限制,默认为int
        show2<std::string ,2>("hello world!");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liyu123__/article/details/81093984