==operator overload only on certain occasions

2019-09-21 17:34发布

问题:

I am making a project that takes in types as templates. The operator== is already overloaded for chars, ints, strings, etc as you know, but if the user decides to pass in a cstring (null terminated character array) I will need to overload the == for that. Can I choose to only overload the operator== when the user uses cstrings, and use the default == when they dont? How would this be accomplished?

回答1:

You can't overload operator== for C strings, because they are pointers and operators can be overloaded if at least one operand is a class or enum. 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 have to add more overloads to support std::string vs const char* comparisons, as pointed out by TonyD in comments.



回答2:

You cannot overload the == operator on a C-string. I am not completely sure why that should be necessary - the C++ string class has defined an implicit conversion from a C-string, and already defines the == operator.



回答3:

You can use type traits 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;
};