引用自《深入浅出MFC》
c++中的template有两种,一种是function,另一种针对class
- 针对function的: 针对class
定义:
template <class T> T power(T base, int
exponent);
使用:
template <class T>
T power(T base, int exponent)
... {
T result = base;
if (exponent == 0) return (T)1;
if (exponent < 0) return (T)0;
while (--exponent) result *= base;
return result;
}
#include <iostream.h>
void main()
... {
int i = power(5, 4);
long l = power(1000L, 3);
long double d = power((long double)1e5, 2)
cout << "i= " << i << endl;
cout << "l= " << l << endl;
cout << "d= " << d << endl;
}
T power(T base, int exponent)
... {
T result = base;
if (exponent == 0) return (T)1;
if (exponent < 0) return (T)0;
while (--exponent) result *= base;
return result;
}
#include <iostream.h>
void main()
... {
int i = power(5, 4);
long l = power(1000L, 3);
long double d = power((long double)1e5, 2)
cout << "i= " << i << endl;
cout << "l= " << l << endl;
cout << "d= " << d << endl;
}
template <class T>
class CThree
... {
public :
CThree(T t1, T t2, T t3);
T Min();
T Max();
private:
T a, b, c;
} ;
template <class T>
T CThree <T> ::Min()
... {
T minab = a < b ? a : b;
return minab < c ? minab : c;
}
template <class T>
T CThree <T> ::Max()
... {
T maxab = a < b ? b : a;
return maxab < c ? c : maxab;
}
template <class T>
CThree <T> ::CThree(T t1, T t2, T t3) :
a(t1), b(t2), c(t3)
... {
return;
}
class CThree
... {
public :
CThree(T t1, T t2, T t3);
T Min();
T Max();
private:
T a, b, c;
} ;
template <class T>
T CThree <T> ::Min()
... {
T minab = a < b ? a : b;
return minab < c ? minab : c;
}
template <class T>
T CThree <T> ::Max()
... {
T maxab = a < b ? b : a;
return maxab < c ? c : maxab;
}
template <class T>
CThree <T> ::CThree(T t1, T t2, T t3) :
a(t1), b(t2), c(t3)
... {
return;
}
使用:
#include
<
iostream.h
>
void main()
... {
CThree<int> obj1(2, 5, 4);
cout << obj1.Min() << endl;
cout << obj1.Max() << endl;
CThree<float> obj2(8.52, -6.75, 4.54);
cout << obj2.Min() << endl;
cout << obj2.Max() << endl;
CThree<long> obj3(646600L, 437847L, 364873L);
cout << obj3.Min() << endl;
cout << obj3.Max() << endl;
}
void main()
... {
CThree<int> obj1(2, 5, 4);
cout << obj1.Min() << endl;
cout << obj1.Max() << endl;
CThree<float> obj2(8.52, -6.75, 4.54);
cout << obj2.Min() << endl;
cout << obj2.Max() << endl;
CThree<long> obj3(646600L, 437847L, 364873L);
cout << obj3.Min() << endl;
cout << obj3.Max() << endl;
}