For simplicity, suppose I want to implement a function that takes two parameters and a predicate that check for equality,
template<typename T, typename TCompare> bool Eq(const T& a, const T& b, const TCompare& cmp) { return cmp(a, b); }
but I also want operator== accepted if the predicate is not passed.
I tried several different approaches, but all this led either to a syntax error, or to "operator ==" was not defined. I even tried replacing the Eq function with
However, I suppose I want to, because most of the STL supports not passing the optional TCompare parameter (std :: sort, std :: set ...).
UPDATE : Thanks to the levis501 suggestion, this is the best way I've found so far:
template<typename T, typename TCompare> bool Eq(const T& a, const T& b, const TCompare& cmp) { return cmp(a, b); // or some lengthy code } template<typename T> bool Eq(const T& a, const T& b) { static std::equal_to<T> EqCmp; return Eq(a, b, EqCmp); }
So, you basically need to create a wrapper that passes std :: equal_to or any other operator-equivalent functor. For some reason, having it as an argument by default does not compile when calling a function without it.