Why isn't my custom bool operator working?

I’m working on a crime game, and trying to run a test when you pick up a clue to determine whether or not it’s a clue you already have. For the moment, the clue struct only has an ID, and for testing purposes I made two and tried to compare them:

USTRUCT(BlueprintType)
struct FClueBase{
	GENERATED_USTRUCT_BODY()

		UPROPERTY(EditAnywhere, BlueprintReadOnly)
		int32 ID;
};

void TestClue(){
FClueBase clue1;
FClueBase clue2;

clue1.ID = 1;
clue2.ID = 2;

if (clue1 == clue2){
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, "Same clue");
}
}

In order to teach the system how to test my struct for equality, I added a custom bool definition in the .cpp:

bool operator==(const FClueBase& lhs, const FClueBase& rhs){
	return lhs.ID == rhs.ID;
}

This produces two identical errors, "Error C2678: binary ‘==’: no operator found which takes a left-hand operand of type ‘FClueBase’ ". That’s the same error I get when I try to compare structs I haven’t made a custom operator for, which makes me assume there’s a problem with how I made my operator, but it looks right to me- am I missing an obvious step somewhere?

I think the problem is “const” i think, as you variable is not “const” compiler can’t find matching operator override.

Also to keep UE4 conventions you should keep operator override as part of struct or class. operator overrides works same as function show you declare them and define them same way in class or struct, only difference is you remove left hand argument and use variables of left hand directly or via “this” as operator override is part of it

in h inside struct decler:

bool operator==(FClueBase& rhs);

in cpp:

bool FClueBase::operator==(FClueBase& rhs){
     return ID == rhs.ID;
}

Hmm, you’re absolutely right on both counts, thank you!! I was completely unaware of the UE4 convention, this is much cleaner :slight_smile:

you should do bool operator==(const FClueBase& rhs) const{ return ID == rhs.ID; }

Hi all,

FYI, this is incorrect. First, defining operators as members is not UE4 standard, but rather legacy and we strive to fix these cases when we encounter them.

Second is that the problem is likely because you didn’t have a declaration of your operator in the header. It’s not to do with const.

If you took your original code and added this line to your header after FClueBase, it should be fine:

bool operator==(const FClueBase&, const FClueBase&);

Steve

I guess i been seeing lot of “Cases” :stuck_out_tongue:

I was getting really mad, until I saw this. Thanks