tempale 函数,template class 的例子
-
#include <iostream>
-
#include <vector>
-
-
using namespace std;
-
-
template <typename T>
-
T compare_fn(T a, T b)
-
{
-
return (a > b ? a : b);
-
}
-
-
template <typename T>
-
void print_vector(const vector<T> & tVec)
-
{
-
cout << "it's vector:" << endl;
-
for (typename vector<T>::const_iterator it=tVec.begin(); it!=tVec.end(); ++it)
-
{
-
cout << *it << " ";
-
}
-
-
cout << endl;
-
}
-
-
template <typename T>
-
class TCompare {
-
public:
-
TCompare(const T a, const T b);
-
-
T maxValue();
-
T minValue();
-
private:
-
T m_tValue1;
-
T m_tValue2;
-
};
-
-
template <typename T>
-
TCompare<T>::TCompare(const T a, const T b)
-
: m_tValue1(a), m_tValue2(b)
-
{
-
-
}
-
-
template <typename T>
-
T TCompare<T>::maxValue()
-
{
-
return (m_tValue1 > m_tValue2 ? m_tValue1 : m_tValue2);
-
}
-
-
template <typename T>
-
T TCompare<T>::minValue()
-
{
-
return (m_tValue1 < m_tValue2 ? m_tValue1: m_tValue2);
-
}
-
-
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
-
-
int main()
-
{
-
cout << compare_fn(4, 5) << endl;
-
cout << compare_fn(6, 3) << endl;
-
cout << compare_fn(3.3, 4.5) << endl;
-
cout << compare_fn('a', 'd') << endl;
-
-
TCompare<int> a(4, 5);
-
TCompare<int> b(6, 3);
-
TCompare<float> c(3.3, 4.5);
-
TCompare<char> d('a', 'd');
-
-
cout << "max:" << a.maxValue() << endl;
-
cout << "min:" << a.minValue() << endl;
-
-
cout << "max:" << b.maxValue() << endl;
-
cout << "min:" << b.minValue() << endl;
-
-
cout << "max:" << c.maxValue() << endl;
-
cout << "min:" << c.minValue() << endl;
-
-
cout << "max:" << d.maxValue() << endl;
-
cout << "min:" << d.minValue() << endl;
-
-
int array_int[] = {1, 2, 3, 4, 5};
-
char array_c[] = {'a', 'b', 'c'};
-
-
vector<int> ivec(array_int, array_int + ARRAY_SIZE(array_int));
-
print_vector(ivec);
-
-
vector<char> cVec(array_c, array_c + ARRAY_SIZE(array_c));
-
print_vector(cVec);
-
-
return 0;
-
}
阅读(1309) | 评论(0) | 转发(0) |