== Operator overloading only in certain cases

I am making a project that accepts types as templates. The == operator is already overloaded for characters, ints, strings, etc., as you know, but if the user chooses to pass to cstring (the null terminated character array), I would need to overload == for that. Can I choose to only overload the == operator when the user is using cstrings, and use the default == when they don't work? How will this be achieved?

-2


source to share


3 answers


You cannot overload operator==

for C strings, because they are pointers, and operators can be overloaded if at least one operand is a class or enumeration. What you can do is create your own comparator function and use it in your code instead of ==

:

template<typename T>
bool my_equal(const T& a, const T& b) {
    return a == b;
}

bool my_equal(const char* a, const char* b) {
    return /* your comparison implementation */;
}

      



Update: you may need to add more overloads to support std::string

vs comparisons const char*

as pointed out in the comments by TonyD.

+1


source


You cannot overload the operator ==

to a C string. I'm not entirely sure why this is needed - the C ++ class has string

defined an implicit conversion from a C string and already defines an operator ==

.



+2


source


You can use type properties to dispatch to the correct function. For example:

#include <type_traits>

template<typename T>
using is_cstring =
    std::integral_constant<bool,
        std::is_same<T, char const*>::value
     || std::is_same<T, char*>::value>;

template<typename T>
class Thingy
{
public:
    bool operator==(Thingy const& rhs) const
    {
        return equal_helper(rhs, is_cstring<T>());
    }
private:
    bool equal_helper(Thingy const& rhs, std::true_type) const
    {
        return strcmp(m_value, rhs.m_value) == 0;
    }

    bool equal_helper(Thingy const& rhs, std::false_type) const
    {
        return m_value == rhs.m_value;
    }

    T m_value;
};

      

0


source







All Articles