C++模板的概念

本文详细使用程序澄清了所谓类模板(class template), 模板类(全特化或者偏特化实例方法)
#include "stdio.h"
#include <iostream>
using namespace std;

// Functor class
class Functor
{
public:
	bool operator () (int a, int b) {
		return a<b;
	}
	void test(){
		cout << "functor is called. " << endl;
	}
};

//Base Template
template<class T, typename datatype>
class Math
{
private:
	T _t;
	datatype _data;
public:
	void print(){
		cout << "datatype value is: " <<  _data << endl;
		bool bCompare = _t(1,2);
		if(true == bCompare){
			cout << "true" << endl;
		}
	}
};

//Partial specialization Template
template <class T>
class Math<T,int>
{
private:
	T _t;
	int _data;
public:
	void print(){
		cout << "partial specialization on Math. " << endl;
		cout << "datatype value is " << _data << endl;
	}
};

//Full speciallization Template
template<>
class Math<Functor*,char*>
{
private:
	Functor* _p;
	char* _c;
public:
	Math(Functor* p,char* c):_p(p),_c(c) {}
	void print(){
		cout << "Full specialization." << endl;
		bool b = (*_p)(1,2);
		cout << _c << endl;
	}

		
};

int main(int argc, void* argv[])
{
	Math<Functor,int> partMath;
	partMath.print();

	Math<Functor,double> newMath;
	newMath.print();

	Functor* p = new Functor();
	char* c = "full";
	Math<Functor*,char*> fullMath(p,c);
	fullMath.print();
}


你可能感兴趣的:(C++模板的概念)