I have this function template
template < class TParam >
bool greaterThan (TParam A, TParam B) {
if (typeid(TParam) == typeid(string)) {
return A.compare(B) > 0; <--------------- Error
} else {
return A > B;
}
}
But the compiler won’t allow me to use this with an int.
I get a compiler error in the place shown above that says
Member reference base type 'int' is not a structure or union.
The if statement does not run if I’m calling the function on an int.
I commented it out and checked. I don’t know whats wrong.
When
TParamisint, with this:You’re trying to call the
comparemethod of anint. Such a method does not exist. What you need is template specialisation so that you can make the template do something special when the type is a certain type:The syntax is a tiny bit foreign but if you read up on it, template specialisation is a very powerful addition to templates.
Note that
stringdoes haveoperator<so you don’t even need to specialise it if you don’t want to, but this is a good opportunity to learn about template specialisation.