函数模板与类模板其实就是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();
}