首页 > 解决方案 > 错误:TSortedMap 以自定义结构为键,重载 operator<

问题描述

我正在尝试以我的自定义结构作为键来实现TSortedMap 。我已经重载了结构的运算符。但是,当我尝试编译时,在向 TSortedMap 添加元素的代码行中出现此错误:

error C2678: binary '<': no operator found which takes a left-hand operand of type 'const T'
(or there is no acceptable conversion)

我的结构:

USTRUCT(BlueprintType)
struct FUtility
{
GENERATED_BODY()

public:

UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(ClampMin = "0.0", ClampMax = "1.0"))
float value = 0.0f;

UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (ClampMin = "0.0", ClampMax = "1.0"))
float weight = 1.0f;

FORCEINLINE bool operator== (const FUtility& other)
{
    return this->value == other.value && this->weight == other.weight;
}

FORCEINLINE bool operator< (const FUtility& other)
{
    return (this->value * this->weight) < (other.value * other.weight);
}

.....

friend uint32 GetTypeHash(const FUtility& other)
{
    return GetTypeHash(other.value) + GetTypeHash(other.weight);
}
};

不太清楚为什么它不编译,因为它已重载。也许它没有正确重载。任何帮助将不胜感激。

标签: structunreal-engine4

解决方案


好吧,奇怪的是我想通了。文档中的所有操作符逻辑都采用了两个参数,这真的让我很烦恼。原来我只是错过了friend关键字。从那里我可以添加第二个参数并且编译得很好。

例子:

friend bool operator< (const FUtility& a, const FUtility& b)
{
    return (a.value * a.weight) < (b.value * b.weight);
}

推荐阅读