How to pass an operator as an argument to a functor by default?

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.

+4
source share
3 answers

You can overload functions, not?

 // Use the user-supplied TCompare. template<typename T, typename TCompare> bool Eq(const T& a, const T& b, TCompare cmp) { return cmp(a, b); } // Use op== for equality otherwise. template<typename T> bool Eq(const T& a, const T& b) { return a == b; } 

If the code calls Eq() with three arguments, the compiler will allow the first overload to be called. If the code calls Eq() with only two arguments, the compiler will have to solve the second overload.

+1
source

I do not think that something like the following will work for you:

 #include <functional> template<typename T, typename TCompare = std::equal_to<T>> class Math { public: static bool Eq(const T& a, const T& b) { TCompare cmp; return cmp(a, b); } }; int _tmain(int argc, _TCHAR* argv[]) { Math<int>::Eq(1,1); return 0; } 

Default template options are only allowed for class templates (or at least what MSVC 10 says)

+1
source

Source: https://habr.com/ru/post/1379253/


All Articles