用C ++编写两个基本类型之间的预先比较(==) [英] Write an oveloaded comparison (==) between two primative types, in C++

查看:48
本文介绍了用C ++编写两个基本类型之间的预先比较(==)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文章指出,不可能重载比较运算符(==)从而使双方都可以采用原始类型.

As pointed out by this article, it is impossible to overload the comparison operator (==) such that both sides could take primitive types.

否,C ++语言要求您的运算符重载至少要使用类类型"或枚举类型的一个操作数.C++语言将不允许您定义所有其操作数/参数均为原始类型的运算符. " ( parashift )

我想知道:

**如果真的需要使用==以非标准方式比较两个基元,是否可以将它们隐式转换为其他类?

**If I really-really needed to compare two primitives in a non-standard way using the ==, is there a way to implicitly cast them to some other class?

例如,以下代码可用于const char*比较,但需要显式强制转换.如果可能的话,我宁愿避免进行明确的强制转换.

For example, the following code will work for const char* comparison, but it requires an explicit cast. I would prefer to avoid explicit casts if possible.

// With an explicit cast
if(string("a")=="A") // True

// Without the cast
if("a"=="A") // False

// An example overloaded function:
bool operator == (string a, const char* b)
{
    // Compares ignoring case
}

在某些情况下,投射可能很笨拙,尤其是当您需要在一个长表达式中进行多次强制转换时.因此,这就是为什么我要寻找一种将第一个输入(或两个输入)自动转换为字符串类型的方法.

Casting can be pretty clunky in some situations, especially if you need to do several casts inside a long expression. So that's why I was looking for a way to automatically cast the first input (or both) to a sting type.


Edit 1:

执行此操作的另一种方法是编写isEqual(const char* a, const char* b)函数,但是我想避免这种情况,因为如果在大型if语句中使用它,则会导致括号混乱.这是一个过于简化的示例,仍然显示了我的意思:

Another way to do this is to write an isEqual(const char* a, const char* b) function, but I want to avoid this because it will result in a mess of parenthesis if I were to use it inside of a large if-statement. Here's an oversimplified example that still shows what I mean:

if (str1 == str2 || str1 == str3 || str2==str4)

相对于:

if (isEqual(str1,str2) || isEqual(str1,str3) || isEqual(str2,str4))


Edit 2:

我知道有很多方法可以实现所需的功能而又不会使==过载.但是我专门寻找一种使==起作用的方法,因为这样我就可以将这些知识也应用于其他运算符.

I know there exist many ways to achieve the desired functionality without overloading the ==. But I looking specifically for a way to make the == work because I then could apply the knowledge to other operators as well.

这个问题实际上与干净代码).

这就是我想在这里问的一个问题,以防有人冒充我不知道的C ++技巧.但是,如果答案为否",那也很好.

And that's I wanted to ask this question here on SO, in case someone had a cool C++ trick up their sleeve that I didn't know about. But if the answer is No then that's fine too.

推荐答案

您当然可以编写一个或多个免费函数进行比较.不必是运算符重载.

You could certainly write one or more free functions to do your comparison. It doesn't have to be an operator overload.

例如:

bool IsEqual(const char* a, const string& b)
{
  // code
}

bool IsEqual(const string& a, const char* b)
{
  // code
}

以此类推.

这篇关于用C ++编写两个基本类型之间的预先比较(==)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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