Is there anyway to specialize a template like this, making the specialization apply only if T has a member function hash? (Note this is only an example of what I am trying to do. I know that it would make more sense for each class that has a hash function to check it on its own in the operator== member function, but I just want to know if this kind of thing is possible.)
template <class T>
bool equals(const T &x, const T &y)
{
return x == y;
}
template <class T> // somehow check if T has a member function 'hash'
bool equals<T>(const T &x, const T &y)
{
return x.hash() == y.hash() && x == y;
}
I would prefer a pre-C++11 solution if possible.
Here’s an example from my own code. As you might guess from one of the structure names this is based on the principle that Substitution Failure is Not an Error. The structure
has_member_setOrigindefines two versions oftest. The first one cannot be satisfied ifUdoes not have a membersetOrigin. Since that is not an error in a template substitution it just acts as if it does not exist. The resolution order for polymorphic functions thus findstest(...)which would otherwise have a lower priority. Thevalueis then determined by the return type oftest.This is followed by two definitions of
callSetOrigin(equivalent to yourequals) using theenable_iftemplate. If you examineenable_ifyou’ll see that if the first template argument is true thenenable_if<...>::typeis defined, otherwise it is not. This again creates a substitution error in one of the definitions ofcallSetOriginsuch that only one survives.Forgot I provided a definition of
enable_ifas well: