this is a very good and nearly concise article to learn about c++ templates
http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part
I will bring essential parts in 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.
You should better use a name that reflects the meaning of type-parameter, and that improves code readability.
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 the function for the type you pass explicitly:
PrintTwice<double>(5);
if you don't pass any type, compiler determines what the type is.
you can have templates of multiple arguments and(optionally) return type same type:
template<class T>
T Add(T n1, T n2)
{
return n1 + n2;
}
but note that you cant for example pass n1
in int
and n2
in double! both arguments should be of the same type and return type is also of that type.
if you want to have a template function of possibly different 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 function-template takes template-type, but not from its function arguments like:
template<class T>
void PrintSize()
{
cout << "Size of this type:" << sizeof(T);
}
You cannot call such function template simply as:
PrintSize();
Since this function template would require template type argument specification, and it cannot be deduced automatically by compiler. The correct call would be:
PrintSize<float>();
2.class templates:
definition is almost similar:
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 should specify the type explicitly:
Item<int> item1;
the tricky part is, you can not implement declarations in header file, and the respective implementation in one or more source files.(please refer to article to see why)
class templates also allow few non-type template arguments:
template<class T, int SIZE>
class Array
{
static const int Elements_2x = SIZE * 2;
void DoSomething(int arg = SIZE);
// Non-const can also appear as default-argument...
private:
T TheArray[SIZE];
};
there is so many other parts and a lot lot more explanation which i can not bring here.
i suggest you spend a few hours and read that article and second part of that article. even if you think you know how templates work in c++.