Skip to main content

C++20 Idioms in Unreal

Idioms

These are common patterns seen in the Unreal Engine source code, not necessarily specific to C++ 20.

Anonymous Enums

For example:

template<>
struct TMassExternalSubsystemTraits<UMassTestGameInstanceSubsystem>
{
enum
{
GameThreadOnly = false,
ThreadSafeRead = true,
ThreadSafeWrite = false,
};
};

This declares the three values specified in the enum without allocating any variables. When the compiler sees the variable TMassExternalSubsystemTraits<UMassTestGameInstanceSubsystem>::GameThreadOnly it substitues the value false. Because no variable is allocated it does not take any memory and the value cannot be changed.

Free friend functions

Consider this code:

struct FMeshSizeKey
{
private:
int32 X = 0;
int32 Y = 0;
int32 Z = 0;

friend uint32 GetTypeHash( const FMeshSizeKey& Key )
{
return HashCombine(
HashCombine(
::GetTypeHash( Key.X ),
::GetTypeHash( Key.Y ) ),
::GetTypeHash( Key.Z ) );
}
};

The friend keyword makes GetTypeHash() a free function, not a member function. Without the friend keyword it would be a member function. The free function exists outside the struct, but has access to the members of the struct, even though they are private.

This technique is used by Unreal to implement hashing. Unreal uses argument dependent lookup to find the GetTypeHash() function based on the argument type FMeshSizeKey.