// template function for a simple addition function
template<typename T> // template parameter list
T Add(T a, T b) // function template name
{
return a+b;
}
// int example
int a = 2;
int b = 2;
int res = Add(a,b); // i.e. int Add(int, int)
// float example
float c = 2.2;
float d = 2.2;
float res2 = Add(c,d); // i.e. float Add(float, float)
————————————————————————————————————————————————
// template class.
template<typename T> // The parameter list
class Foo // The template name id
{
public:
// constructor
Foo(){}; // default
Foo(T val):iVal(val){}
// Modifiers & Accessors
void Set(T val){iVal=val;}
T Get()const {return iVal;}
private:
T iVal;
};
// in use
Foo<int> foo(0); // Builds an int iVal class
Foo<float> boo(0.0); // Builds a float iVal
————————————————————————————————————————————————
template <typename T, typename C>
class Bar : public Foo<T> // this is using a template
{
public:
// ...
private:
C iDerivedVal;
};
// in use
Bar<int, float> bar;
bar.Set(42);
————————————————————————————————————————————————
// Generic
template<typename T> // template parameter list
T Add(T a, T b) // function template name
{
return a+b;
}
// Specialization
// The empty parameter list tells the compiler it is dealing with
// a specialization:
template<>
char* Add<char*>(char* a,char* b) // Template argument list
{
return strcat(a,b);
}
// In use
char* res = Add<char*>("foo","bar"); // note different syntax
int n = Add(2,2); // calling the int version
————————————————————————————————————————————————
template<typename T, int size>
68 CLASS DESIGN AND INHERITANCE
class Foo
{
T iElements[size]; // an array of Ts
};
// In use
Foo<int,10> foo; // Creates an array of 10 integers
————————————————————————————————————————————————————