this is a very good and almost brief article to learn about C ++ templates
http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part
I will provide important details here:
1. function templates:
simple function template:
template<class TYPE> void PrintTwice(TYPE data) { cout<<"Twice: " << data * 2 << endl; }
note that "TYPE" can be any other valid name.
It is better to use a name that reflects the value of the type parameter and improves the readability of the code.
now you can call it like this:
PrintTwice(5.5);//TYPE is 'float' PrintTwice(5);//TYPE is 'int'
you can force the compiler to instantiate a function for the type that you pass explicitly:
PrintTwice<double>(5);
if you do not pass any type, the compiler determines the type.
you may have templates with multiple arguments and (optionally) a return type:
template<class T> T Add(T n1, T n2) { return n1 + n2; }
but note that you cannot, for example, pass n1 to int and n2 to double! both arguments must be of the same type, and the return type also applies to this type.
if you want to have a template function, perhaps another type argument:
template<class T1, class T2> double Add(T1 t1Data, T2 t2Data) { return t1Data + t2Data; }
and use it like:
cout<<Add(5,7.0);//T1=int T2=double cout<<Add(5.5,7);//T1=double T2=int cout<<Add<double,double>(5,7);//T1=double T2=double by passing types explicitly
When a function template accepts a template type, but not from its function arguments, for example:
template<class T> void PrintSize() { cout << "Size of this type:" << sizeof(T); }
You cannot call a function template such as:
PrintSize();
Since this function template will require a specification of the template type argument, and it cannot be automatically output by the compiler. Correct call:
PrintSize<float>();
2.class templates:
Definition
almost looks like:
template<class T> class Item { T Data; public: Item() : Data( T() ) {} void SetData(T nValue) { Data = nValue; } T GetData() const { return Data; } void PrintData() { cout << Data; } };
but when using it, you must explicitly specify the type:
Item<int> item1;
the tricky part is that you cannot implement the declarations in the header file and the corresponding implementation in one or more source files (refer to the article to find out why)
Class Templates
Also, several non-piggy type template arguments allow:
template<class T, int SIZE> class Array { static const int Elements_2x = SIZE * 2; void DoSomething(int arg = SIZE);
there are so many other parts and many more explanations that I cannot bring here.
I suggest you spend a few hours and read this article and the second part of this article. even if you think you know how templates work in C ++.