Overload Equality Operator (==) to compare String and Int

c++ overload comparison operator
c# not equal string
overload comparison operator c++ struct
c++ program to compare two strings using operator overloading
c++ default comparison operator
comparison operators
c# comparison operators
logical operator overloading in c++

I am experiencing with protocols and challenged myself to write a code snippet that overloads the == operator so that it returns true when I compare a random String with value "42" with a Int of value 42. Please don't question the usefulness by simply returning 42 on a String, the main point is getting the Equality Operator to run on the two different types.

Here is what I tried:

Version 1
import Foundation

protocol IntTransformable: Equatable {
    func toInt() -> Int
}

extension String: IntTransformable {
    func toInt() -> Int {
        return 42
    }
}

extension Int: IntTransformable {
    func toInt() -> Int {
        return self
    }
}

extension IntTransformable {
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.toInt() == rhs.toInt()
    }
}

// throws: Ambiguous reference to operator function '=='
if "42" == 42 {
    print("equal")
} else {
    print("unequal")
}
Version 2
import Foundation

protocol IntTransformable: Equatable {
    func toInt() -> Int
}

extension String: IntTransformable {
    func toInt() -> Int {
        return 42
    }
}

extension Int: IntTransformable {
    func toInt() -> Int {
        return self
    }
}

extension IntTransformable {
    // throws: Protocol 'IntTransformable' can only be used as a generic constraint because it has Self or associated type requirements
    static func == (lhs: IntTransformable, rhs: IntTransformable) -> Bool {
        return lhs.toInt() == rhs.toInt()
    }
}

// throws: Ambiguous reference to operator function '=='
if "42" == 42 {
    print("equal")
} else {
    print("unequal")
}

You should use these two functions:

func ==(lhs: String, rhs: @autoclosure ()->Int) -> Bool {
    guard let stringIntValue = Int(lhs) else { return false }
    return stringIntValue == rhs()
}

func ==(lhs: Int, rhs: String) -> Bool {
    guard let stringIntValue = Int(rhs) else { return false }
    return lhs == stringIntValue
}

But if you really want to involve Protocols here, you should do this like:

extension IntTransformable {
    static func ==<T: IntTransformable>(lhs: Self, rhs: T) -> Bool {
        return lhs.toInt() == rhs.toInt()
    }
}

Usage:

print( 42 == "42" )
print( "42" == 42 )

9.6, Overloading the comparison operators is comparatively simple (see what I did there?), Car(const std::string& make, const std::string& model) Int in the above example is just to indicate type of x and y, not be correct code. If a reference type overloads the == operator, use the Object.ReferenceEquals method to check if two references of that type refer to the same object. String equality. Two string operands are equal when both of them are null or both string instances are of the same length and have identical characters in each character position:

You're way overthinking this. There is no reason to use protocols here, and you really can't do it because protocols are not really types. Just write your operator(s) at top level:

func == (lhs: Int, rhs: String) -> Bool {
    return lhs == Int(rhs)
}
func == (lhs: String, rhs: Int) -> Bool {
    return Int(lhs) == rhs
}

Testing:

print(5 == "5") // true

Comparison operators, However, in a user-defined operator overload, any type can be used as return type (including void). T2 can be any type including T  C++ program to compare two Strings using Operator Overloading Pre-requisite: Operator Overloading in C++ Given two strings, how to check if the two strings are equal or not, using Operator Overloading.

create a string extension, like

public string ToInt(this int value) { // some conversion code

return ConvertedStringValue; }

or you can use a uint.TryParse(string value, out uint output) this statement will return true if conversion is successful.

C++ program to compare two Strings using Operator Overloading , // and right operand string are equal. //(else return 0/false). int operator==(​CompareString s2). In this case, I chose not to do so because the function definitions are so simple, and the comparison operator in the function name line up nicely with the comparison operator in the return statement. Quiz time. 1) For the Cents example above, rewrite operators < and <= in terms of other overloaded operators. Show Solution

Equals overloading in Kotlin, Probably correct equals + hashCode implementations on object s technical reason stops Kotlin from resolving the overloaded operator, As for now (Kotlin 1.0.2 EAP), even with declared supertype you can only check object 's equality Int = 5 private val STRING: String = "foo" override fun equals(other:  In C, string values (including string literals) are represented as arrays of char followed by a 0 terminator, and you cannot use the == operator to compare array contents; the language simply doesn't define the operation.

Why didn't == operator string value comparison make it to Java , Java doesn't allow users to overload operators - therefore reference equality is testing whether an object is a boxed integer with particular value (comparison  What's the right way to overload operator== for these classes? If I make them all free functions, then B and C can't leverage A's version without casting. It would also prevent someone from doing a deep comparison having only references to A. If I make them virtual member functions, then a derived version might look like this:

Equality in Kotlin ('==', '===' and 'equals'), This brings in another question, which equality check should we use in which case. operator in Kotlin only compares the data or variables, whereas in Java or other First, let's compare two primitive type Int variables by all the equal checks. But in the case of string comparison, if only checks the contents of the string  Browse other questions tagged c++ operators operator-overloading operator-keyword or ask your own question. The Overflow Blog The Overflow #26: The next right thing

Comments
  • You can get your protocol working as simply as static func == (lhs: Self, rhs: Self) -> Bool { return lhs.toInt() == rhs.toInt() } However, using the operator on a String and Int will still result in the same error.
  • You can't do this using a protocol because of the ways in which a protocol is not really a type.
  • @DávidPásztor thanks for the code improvement hint.
  • @matt if I cannot use a protocol, what could I do instead?
  • BTW, if you want to introduce different ideas of equality for a type T, I would recommend you make a struct that wraps a T, and conforms to equatable by implementing the new definition of equality. Defining == over existing types usually leads to this sort of ambiguity/mess
  • In your second example I guess you meant return lhs.toInt() == rhs.toInt()
  • i think the purpose of the protocol is to have multipole cases of comparisons. Like, Double, Float, Int32, Char etc. Having the first solution in this case would be a lot of different functions
  • @Vollan toInt() limited it to Int, Then he should consider using overloads of the function, instead of using this strict protocol.
  • The protocol version does not work for me and why are you using an autoclosure in the tow functions?
  • @MojtabaHosseini got it, thanks mate! I just read through another article about it and it got clearer. I missed the point that the argument itself could be passed as a function/method/. Thanks for your help. Learned a lot here.
  • I was also trying to get around defining the operator on a global level, but I guess you are right when you say I am overthinking this.
  • @ChrisGraf You can declare them as an extension to Int as well if that makes any difference
  • Operators aren't namespaced. == is ==, whether defined in a struct or in at the top level. It doesn't really make any difference
  • @Alexander The thing I was trying to get away from is the Self / IntTransformable cuteness in the OP's code. Plain and simple is often best. "Say what you mean" is a programming koan.
  • @matt My comment was in response to Chris' "trying to get around defining the operator on a global level"