Format:
- template <class identifier> function_declaration;
-
template <typename identifier> function_declaration;
Use:
- function_name <type> (parameters);
Example:
- #include <iostream>
-
using namespace std;
-
-
template <class T>
-
T GetMax (T a, T b)
-
{
-
T result;
-
result = (a > b) ? a : b;
-
return (result);
-
}
-
-
int
-
main(void)
-
{
-
int i=5, j=6, k;
-
long l=10, m=5, n;
-
k = GetMax<int>(i,j);
-
n = GetMax<long>(l,m);
-
-
cout << k << endl;
-
cout << n << endl;
-
-
return (0);
-
}
Class template:
- #include <iostream>
-
using namespace std;
-
-
template <class T>
-
class mypair {
-
T a, b;
-
public:
-
mypair (T first, T second) {
-
a = first;
-
b = second;
-
}
-
T getmax();
-
};
-
-
template <class T>
-
T mypair<T>::getmax()
-
{
-
T retval;
-
retval = a > b ? a : b;
-
return retval;
-
}
-
-
int
-
main(void)
-
{
-
mypair<int> myobject (100, 75);
-
cout << myobject.getmax() << endl;
-
-
return (0);
-
}
Template specialization:
- #include <iostream>
-
using namespace std;
-
-
template <class T>
-
class mycontainer {
-
T element;
-
public:
-
mycontainer (T arg) {element = arg;}
-
T increase () {return (++element);}
-
};
-
-
template <>
-
class mycontainer<char> {
-
char element;
-
public:
-
mycontainer (char arg) {element = arg;}
-
char uppercase() {
-
if ((element >= 'a') && (element <= 'z'))
-
element += 'A'-'a';
-
return (element);
-
}
-
};
-
-
int
-
main(void)
-
{
-
mycontainer<int> myint (7);
-
mycontainer<char> mychar ('j');
-
cout << myint.increase() << endl;
-
cout << mychar.uppercase() << endl;
-
-
return (0);
-
}
- #include <iostream>
-
using namespace std;
-
-
template <class T, int N>
-
class mysequence {
-
T memblock [N];
-
public:
-
void setmember (int x, T value);
-
T getmember (int x);
-
};
-
-
template <class T, int N>
-
void mysequence<T, N>::setmember(int x, T value)
-
{
-
memblock[x] = value;
-
}
-
-
template <class T, int N>
-
T mysequence<T, N>::getmember(int x)
-
{
-
return memblock[x];
-
}
-
-
int
-
main(void)
-
{
-
mysequence<int, 5> myints;
-
mysequence<double, 5> myfloats;
-
myints.setmember(0,100);
-
myfloats.setmember(3, 3.1416);
-
cout << myints.getmember(0) << endl;
-
cout << myfloats.getmember(3) << endl;
-
-
return (0);
-
}
Because templates are compiled when required, this forces a restriction
for multi-file projects: the implementation (definition) of a template
class or function must be in the same file as its declaration. That
means that we cannot separate the interface in a separate header file,
and that we must include both interface and implementation in any file
that uses the templates.
Since no code is generated until a template is instantiated when
required, compilers are prepared to allow the inclusion more than once
of the same template file with both declarations and definitions in a
project without generating linkage errors.
阅读(930) | 评论(0) | 转发(0) |