Search code examples
c++macrosunreal-engine4

Meaning of the syntax "ContextRegistrar_##ContextType"


I am struggling to understand what the following #define does exactly.

#define REGISTER_CONTEXT( ContextType ) static const FContextRegistrar ContextRegistrar_##ContextType( ContextType::StaticClass() );
REGISTER_CONTEXT(UBlueprintContext);

As far as i know it adds a UClass to an array, so that it can be used by a other function and iterated through. But what does the

ContextRegistrar_##ContextType

do in this context? Can anyone give me a hint please? This is causing me an runtime crash and I couldn't find something similar.

This is the corresponding struct:

struct FContextRegistrar
{
    static TArray<TSubclassOf<UBlueprintLibraryBase>>& GetTypes()
    {
        static TArray<TSubclassOf<UBlueprintLibraryBase>> Types;
        return Types;
    }

    FContextRegistrar( TSubclassOf<UBlueprintLibraryBase> ClassType )
    {
        GetTypes().Add( ClassType );
    }
};

Solution

  • ## is a token pasting operator in C and C++ preprocessor. You can create new tokens using it. For example:

    #define MACRO(x) x ## 1

    This macro creates a new token that is same as its argument x, but with 1 appended to it. If you invoke it like MACRO(1) the result would be integer literal 11, result of MACRO(a) would be a1 which you could use as a name of variable, function, class, etc.

    In your example the REGISTER_CONTEXT(UBlueprintContext); would produce the following code:

    static const FContextRegistrar ContextRegistrar_UBlueprintContext( UBlueprintContext::StaticClass() );