C++类模板与函数模板 & 类模板继承

函数模板与类模板其实就是Java里面的泛型编程,只作为抽象的模板,使用时需要指定具体的类型才能实例

下面就看类模板最典型的案列就能明白了:

#include <iostream>
#include <initializer_list>
#include <string.h>

using namespace std;

//类模板
template<class T,int n>
class Myarray{

public:
	T* p;

	Myarray(const initializer_list<T>& list){
		cout << "cons two" << endl;
		p = new T[n];
		memset(p, 0, sizeof(T)* n);
		int length = list.size();
		if (length > n){
			abort();
		}
		else{
			int i = 0;
			for (auto j : list){
				p[i] = j;
				i++;
			}
		}

	}


	void show(){
		for (int i = 0; i < n; i++){
			cout << p[i] << endl;
		}
	}
	
	~Myarray(){
		
	}

};


void main(){

	Myarray<int, 5> myarray{1,2,3,4,5};
	myarray.show();

	Myarray<double, 3> mystring{1.2,2.3,4.4};
	mystring.show();

	cout << typeid(Myarray<string, 12>).name() << endl;

	cin.get();
}



二:类模板与类模板的继承必须保持类型一致,类模板与普通类的继承需要指定明确的类型

先看代码才能了解到底是怎么一回事,模板编程只能自己去理解。

#include <iostream>

using namespace std;


// T 与 T  支持继承  多台
// T 与 P 之间


template<class T>
class Father{

public:
	T data;

	void show(){
		cout << data << endl;
	}

	virtual void go(){
		cout << "father go" << endl;
	}

};



template<class T>
class Son : public Father<T>{

public:

	void go(){
		cout << "son go" << endl;
	}

};



void main(){

	//Son<int> myson;
	//myson.data = 100;

	//myson.Father::show();

	//模板类的集成 也能实现多态
	Father<int> * father = new Son<int>;
	father->go();


	cin.get();
}

模板与普通类之间的继承:

#include <iostream>
using namespace std;

template<class T>
class Teacher{

public:
	T data;

	void show(){
		cout << data << endl;
	}

	virtual void go(){
		cout << "teacher go" << endl;
	}
};

class Son : public Teacher<int>{

};



到这边就应该能看懂类模板了,现在将以下函数模板里的一个知识点就是类包装器,本质就是伪函数如何在函数模板中使用

很容易联想到函数包装器的使用,可以参考我之前写的博客http://blog.csdn.net/szqsdq/article/details/62423313

#include <iostream>
#include <list>

using namespace std;


//函数模板
template<class T,class F>
T testFunc(T t,F func){
	return func(t);
}

template<class T>
class Teacher{

public:

	Teacher(){
		cout << "kong constructer" << endl;
	}

	Teacher(const T& t){
		cout << "constructer" << endl;
	}

	T operator()(T data){
		for (auto i : data){
			cout << i << endl;
		}
		return data;
	}

};





void main(){

	list<int> mylist;
	for (int i = 0; i < 5; i ++){
		mylist.push_back(i);
	}

	/*testFunc(mylist, [](list<int> tlist){
		for (auto i : tlist){
			cout << i << endl;
		}
		return tlist;
	});*/

	
	Teacher<list<int>> temp;
	testFunc(mylist, temp);

	cin.get();
}




  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值