==操作员仅在某些情况下过载 [英] ==operator overload only on certain occasions

查看:114
本文介绍了==操作员仅在某些情况下过载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个将类型作为模板的项目.如您所知,运算符==已经对char,int,string等进行了重载,但是如果用户决定传入cstring(以null终止的字符数组),则需要为此==重载.我可以选择仅在用户使用cstring时重载operator ==,而在不使用cstring时使用默认==吗?这将如何实现?

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?

推荐答案

对于C字符串,不能重载operator==,因为它们是指针,并且如果至少一个操作数是类或枚举,则可以重载运算符.您可以做的是创建自己的比较器函数,然后在代码中使用它,而不是使用==:

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

更新:正如TonyD在评论中指出的那样,您可能必须添加更多重载以支持std::stringconst char*比较.

Update: you may have to add more overloads to support std::string vs const char* comparisons, as pointed out by TonyD in comments.

这篇关于==操作员仅在某些情况下过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆