I'm learning C ++ right now, and now I know the basic concept of a template that acts as a generic type, and I found almost all the templates used in C ++, So what I really want to know is when should we use a template? Can someone complete their experience for me about the C ++ template? When will you consider using a template?
Addendum:
if we defined such a function
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
but we want to pass an object (a self-defined class) for comparison, how can we implement it?
Supplement2:
in the answer below, someone wrote this sample code
template <class myType>
const myType& GetMax (const myType& a, const myType& b) {
return (a<b?b:a);
}
template <class myType, class Compare>
const myType& GetMax (const myType& a, const myType& b, Compare compare) {
return (compare(a,b)?b:a);
}
It is right? can we just pass the name of the function as a parameter to the myType class?
source
share