Templates Comparision

How do I compare two variables who do not have a predefined Type (i.e Templates).
If I just do a==b it only works for integers and not for strings. Is there any general method present for comparing templates.
1
2
3
4
5
template <typename T1, typename T2>
bool operator ==( const T1 &lhs, const T2 &rhs )
{
   return ( lhs == rhs );
}
The operator== works fine with C++ std::strings.
http://cplusplus.com/reference/string/basic_string/operators/

How do I compare two variables who do not have a predefined Type (i.e Templates).

You overload the comparison operators you need.

1
2
3
4
5
6
7
bool operator == (CustomType a, CustomType b)
{
    if (/* you determine that a is equal to b */)
        return true;

    return false;
}

@ vlad: your code looks recursive to me.
> How do I compare two variables who do not have a predefined Type (i.e Templates).

a. The type involved must have an == operator,
or b. std::equal_to<> must have been specialized for the type
or c. the user must providede a binary predicate which can be used for comparing objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <functional>
#include <iostream>
#include <string>

template < typename T, typename PREDICATE = std::equal_to<T> > 
struct foo
{
    explicit foo( const PREDICATE& c = PREDICATE() ) : cmp_eq(c) {}

    void compare_them( T a, T b )
    {
        if( cmp_eq(a,b) ) std::cout << "equal\n" ;
        else std::cout << "not equal\n" ;
    }

    private: PREDICATE cmp_eq ;
};


int main()
{
    foo<int> x ; // built in == for int
    x.compare_them( 17, 27 ) ; // not equal

    std::string a = "abcd", b = "abcd" ;

    foo<std::string> y ; // overloaded == for std::string
    y.compare_them( a, b ) ; // equal

    // user defined binary comparison predicate
    std::function< bool( int, int ) > eq_last_digit =
                  [] ( int a, int b ) { return a%10 == b%10 ; } ;

    foo< int, std::function< bool( int, int ) > > z(eq_last_digit) ; 
    z.compare_them( 17, 27 ) ; // equal
}
I'm using the code posted by vlad above as a class member function and it displays and error:
operator == must take exactly one input argument
> I'm using the code posted by vlad above

The code posted by vlad above is for a free function.

Do not, repeat, do not even think of using it; it is broken for more than one reason.

If neither T1 nor T2 is a user defined type, it will result in a compile-time error.

If it does not result in a compile-time error, it will cause an infinite recursion at run-time; the operator== will never return.
Topic archived. No new replies allowed.