(templates) - , . , .
++, .
:
template < typename T >
Tabs (T _value)
{
return (_value < 0)? - value: value;
}
template , . - typename T , T. .
:
● (typename T);
● (T _value).
, - , .
typename class. . typename , T , , int. , class , .
T , .
, . , !
. (instantiation) . T :
std::cout << abs< double >(-2.5);
std::cout << abs< int >(-2);
std::cout << abs< Money>(Money(-5, 20)).m_dollars;
(deducted) :
std::cout << abs(-2.5);
std::cout << abs(-2);
std::cout << abs(Money(-5, 20)).m_dollars;
T . , T.
- , .
|
|
:
short x = 20000;
int result = add< int, char, short >(a, x);
:
short x = 20000;
int result = add< int >(a, x);
.
, . . , template < typename T> . .
, , . , . , , . , , - !
#include <iostream>
template < typename T>
class Test
{
public:
void f (T x)
{
// -, , T !
* x = 5;
}
void g ()
{
std::cout << "Saying hello!" << std::endl;
}
};
int main ()
{
// int.
// int, f, ,
// , f!
Test< int > t;
t.g();
}
- . , Test<int> Test<short> - , .
, . , , . - Test<int> Test<short>, , :
#include <iostream>
template < typename T >
class Test
{
public:
static int ms_objectCounter;
public:
Test () { ++ ms_objectCounter; }
Test (const Test< T > & _t) { ++ ms_objectCounter; }
};
int Test< int >::ms_objectCounter;
int Test< short >::ms_objectCounter;
int main ()
{
Test< int > ti1;
Test< int > ti2 = ti1;
std::cout << Test< int >::ms_objectCounter << std::endl;
|
|
std::cout << Test< short >::ms_objectCounter << std::endl;
}
, - :
template < typename T = int >
class Test
{
//...
};
- . :
1. . , , , :
//
Stack (int _size = 10);
, :
//
Stack< T > & operator = (const Stack< T >& _s);
2. , , . , :
template < typename T >
Stack< T >::Stack (int _size)
: m_size(_size)
{
m_pData = new T[ m_size ];
m_pTop = m_pData;
}
3. . , (inline). CPP- - . . , C++, . , .
4. , . - ? , (, char) :
void push (const T& _value);
(explicit instantiation). , CPP- . , , MyTemplate - int std::string. mytemplate.cpp :
template class MyTemplate< int >;
template class MyTemplate< std::string >;
, MyTemplate , , . , CPP-, .
, , , , . , . - .. .