templates
function templates
- template functions
- steps from formulating a template definition to instancing
- general form of a template function
template <class T>
void f(T param)
{
// ..... function body
} |
notes
- each word in angle brackets must begin with "class" which refers to class of data type, not to class
- here "T param" is just a placeholder which will be filled in when the function is called
- in other words, "T" is just a place-holder
- declaring the prototype
- the prototype is declared as the following for the class TMyClass:
template TMyClass * Copy(const TMyClass ¶m); |
-
- the template is used to construct the actual function
template classes
- sample declaration
template <class T>
class TAnyClass {
// ... class members
};
|
notes
- the first word class is for the datatype to be used in the class TAnyClass
- the rest of the declaration after the first is a real class definition
template <class T>
class TAnyClass {
private:
T var;
public:
TAnyClass(T arg): var(arg) { }
};
|
-
layout of the files for template specs
Implementing template member functions is somewhat different than implementing the regular class member functions. The declarations and definitions of the class-template member functions should all be in the same header file. Why do the declarations and definitions need to be in the same header file? Consider the following:
//B.h
template <class t>
class b
{
public:
b() ;
~b() ;
} ;
|
// B.cpp
#include “B.h”
template <class t>
b<t>::b()
{
}
template <class t>
b::~b()
{
} |
//main.cpp
#include “B.h”
void main()
{
b bi ;
b bf ;
}
|
When compiling B.cpp, the compiler has both the declarations and the definitions available. At this point, the compiler does not need to generate any definitions for template classes, since there are no instantiations. When the compiler compiles main.cpp, there are two instantiations: template classes B and B. At this point, the compiler has the declarations but no definitions!
microsoft- and gnu-specific template declaration
there are two source project in the code/c/microsoft section. One is for class template, the other for a function template.
attempting to convert gnu c++ code to microsoft
- deleted from between the "#include .." declarations and the main() {... (the following were present in the gnu c++ coding version
template int min(int, int);
template double min(double, double);
template char min(char, char);
template int max(int, int);
template double max(double, double);
template char max(char, char);
- deleted the "#pragma implementation ..." directive
return to top