Unreal Engine (UE4 UE5) Custom TMap Key Value Type

Preface

In the development scenario, when you encounter the use of TMap, change the key value type to the custom data type in the project. If no additional coding is done, errors will occur during compilation. Unreal Engine has additional requirements for the data type that you want to use as a TMap key value. It must meet the implementation of hash sequences and conventional comparison operator overloading. The following code simply shows you how to customize the TMap key value type.

Operation

1. Declare the structure type (in the header file), and pay attention to implementing the comparison overloading operation (this is required).

 1//Declared in the header file
 2struct FMapKey
 3{
 4public:
 5int32 KeyID;
 6
 7bool operator ==(const FMapKey& Other) const
 8{
 9return KeyID == Other.KeyID;
10}
11};

The KeyID is used for testing, mainly to compare whether two MapKeys are the same (a data basis for comparison rules)

2. Build a global Hash function to convert FMapKey to Hash

1//Declared in the global domain, I declared it defined in the header file
2inline uint32 GetTypeHash(const FMapKey& Explain)
3{
4return Explain.KeyID;//No actual Hash operation is performed, just use KeyID as a Hash value
5}

The main purpose of this function is to convert key values ​​to Hash values. The algorithm is provided and maintained by the designer, and the engine only needs a uint32 value. The hash algorithm should ensure that different key values ​​have different results, and the same key value has the same result.

Conclusion

The types that can be used as TMap key values ​​are: basic data types, pointers, and individual custom types of Unreal. Therefore, it is very necessary to expand the key value type and add your own type as the key value type.

Engine version: 4.27.2

Translations:

Comment