As pointed out by this article, it is impossible to overload the comparison operator (==) such that both sides could take primitive types.
"No, the C++ language requires that your operator overloads take at least one operand of a "class type" or enumeration type. The C++ language will not let you define an operator all of whose operands / parameters are of primitive types." (parashift)
I was wondering:
**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?
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:
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)
As opposed to:
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.
This question is in fact closely related to the Wacky Math Calculator question I asked a few weeks ago, and being able to overload the == will help make the code look considerably nicer (visually, but perhaps not in a "clean code" way).
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.
No, there's no way to implicitly cast the primitive types the way you want.
The only way to achieve the desired functionality is either by explicitly casting the inputs into another class as stated in the question, or by creating a free function as shown by @Logicat.
If the types of the operands are given, and you cannot add an overload for equality, because
there are just two options:
BTW: That standard-library containers and algorithms often can be customized three ways:
You could certainly write one or more free functions to do your comparison. It doesn't have to be an operator overload.
for example:
and so on.