1. 程式人生 > >c++ 模板函式,類模板,仿函式使用例項程式碼

c++ 模板函式,類模板,仿函式使用例項程式碼


1.模板函式 

#include <iostream>

using namespace std;

template <class T>
T myMin(T x, T y)

return (x < y) ? x : y;
}


void main( )
{
int n1 = 2, n2 = 10;
double d1 = 1.5, d2 = 5.6;
cout<< "較小整數:"<< myMin(n1,n2) << endl;
cout<< "較小實數:"<< myMin(d1,d2) << endl;


system("PAUSE");


}

2.類模板

classtemplate.h

#ifndef _CLASS_TEMPLATE_H_
#define _CLASS_TEMPLATE_H_


#include <iostream>


using namespace std;


namespace classtemplate
{
template<typename T1, typename T2>
class myClass
{
public:
myClass(T1 a, T2 b);
void show();


private:
T1 I;
T2 J;
};


template<typename T1, typename T2>
myClass<T1, T2>::myClass(T1 a, T2 b) : I(a), J(b)
{


}


template<typename T1, typename T2>
void myClass<T1, T2>::show()
{
cout << "I=" << I << ", J=" << J << endl;
}
}


#endif

TestMain.cpp

#include <iostream>
#include "ClassTemplate.h"


using namespace std;
using namespace classtemplate;


void main()
{
myClass<int, int> class1(3, 5);
class1.show();


myClass<int, char> class2(6, 'a');
class2.show();


myClass<double, int> class3(2.9, 10);
class3.show();


system("PAUSE");
}

3.使用模板型別

#include <iostream>
#include <list>
#include <vector>


using namespace std;


template<typename T>
void print(T v)
{
T::iterator itor;
for (itor = v.begin(); itor != v.end(); ++itor)
{
cout << *itor << " ";
}
cout << endl;
}


void main()
{
list<int> l;
l.push_back(1);
l.push_front(2);
if(!l.empty())
print(l);


vector<int> vec;
vec.push_back(1);
vec.push_back(6);
if(!vec.empty())
print(vec);


system("PAUSE");
}

4.仿函式

#include <iostream>


using namespace std;


class DoSome
{
public:
void operator()(int i);
};


void DoSome::operator()(int i)
{
cout << i << endl;
}


void main()
{
DoSome doSome;
doSome(10);


system("PAUSE");
}