Why can't I execute TArray.Contains() with a struct?

I’m trying to work out how the heck to write custom == operators, and I’m really having an incredible amount of trouble figuring out what I’m doing wrong. I know there’s something wrong with what I’m doing, but I can’t figure out exactly what. In my header file, below the #includes and above my UCLASS() dec, I define the struct as per usual, and include the declaration for my operator:


USTRUCT(BlueprintType)
struct FTestStruct{
	GENERATED_USTRUCT_BODY()
		UPROPERTY(BlueprintReadOnly)
		FString name;
	bool operator==(const FTestStruct& lhs);
};

In the .cpp, I add the actual comparing logic:



bool FTestStruct::operator==(FTestStruct& lhs){
	return name == lhs.name; //Return true iff both structs' name string is the same
}

Now at least to my eyes, this looks right, and operations of the format “struct == struct” resolve correctly. However, it fails to compile the instant I try to use this with arrays. The following, for example, gives me an error “binary ‘==’: no operator found which takes a left-hand operand of type ‘const FTestStruct’ (or there is no acceptable conversion)”. Then immediately below that, it gives me a reference to the line in the .cpp my matching logic starts, and says “could be bool FTestStruct::operator ==(const FTestStruct&)”.

FTestStruct tempStruct;
TArray<FTestStruct> testArray;
if (testArray.Contains(tempStruct))
//Do stuff

The problem seems to obviously be that it’s not recognizing my definition to my declaration, but I can’t for the life of me figure out what needs to change in order for the compiler to understand that I’m trying to match the two in my array.

You need to use const reference AND you need to mark the operator as const.



bool FTestStruct::operator==(const FTestStruct& arg) const{
...
}


Non-const reference pretty much indicates you’ll write into that value from within the operator. non-const method (operator is a method) indicates that object can change when you call the method. That’s not what container like TArray would want.

Also, those operators can be defined as:



static bool FTestStruct::operator==(const FTestStruct &arg1, const FTestStruct &arg2{
    return arg1.name == arg2.name;
}


Also see Comparison operators - cppreference.com

Edited to change: never mind, I was being a moron; your suggestion fixes everything, thank you! The reference on comparison operators was a big help, it never occurred to me to seek a centralized reference. :slight_smile: