Библиотека STL (Standart Template Library)
Страница 4. Шаблоны классов


Шаблоны классов

В прошлый раз я заикнулся про шаблоны классов. Раз сказал надо показать. Шаблоны классов очень сильно похожи на шаблоны функций и решают теже задачи. То есть они помогают производить одинаковые операции с разными типами данных. Давайте прошлый пример переложим на классы:

#include "stdafx.h"
#include "iostream.h"

class CFucntInt
{
public:
CFucntInt(int value)
{
x=value;
}
int GetValue()
{
return (x*x)-(2*x);
}
private:
int x;
};

class CFucntDouble
{
public:
CFucntDouble(double value)
{
x=value;
}
double GetValue()
{
return (x*x)-(2*x);
}
private:
double x;
};

void main()
{
CFucntInt cI(25);
CFucntDouble cD(3.12);
cout << "CFunctInt " << cI.GetValue() << endl;
cout << "CFucntDouble " << cD.GetValue() << endl;
}

Ну, а теперь с шаблоном !!!

#include "stdafx.h"
#include "iostream.h"

template < class T >
class Funct
{
public:
Funct(T value)
{
x=value;
}
T GetValue()
{
return (x*x)-(2*x);
}
private:
T x;
};

void main()
{
Funct< int > cI(25);
Funct< double > cD(3.12);
cout << "cI " << cI.GetValue() << endl;
cout << "cD " << cD.GetValue() << endl;
}

Ну как ??? Впечатляет ??? Обратите внимание на Funct< int > cI(25); именно здесь задается тип класса. Это немного непревычно.

 
« Предыдущая статья   Следующая статья »