==operator overload only on certain occasions

末鹿安然 提交于 2019-12-13 11:05:03

问题


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;
};


来源:https://stackoverflow.com/questions/27220464/operator-overload-only-on-certain-occasions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!