How to initialize static TMap?

Header:

// Use a struct because I need a TArray inside the TMap
USTRUCT(BlueprintType)
struct FWBList{..}

static TMap<EStructureCategory, FWBList> WBMap;

CPP:

// Statics in c++ MUST be initialized in order to prevent linker errors.
TMap<EStructureCategory, FWBList> ABaseStructure::WBMap;
// ... erm... How to initialize it now? TMap has no initializer and I'm now allowed to use .Add() here.

Problem is mainly that the TMap has no initializer. I cannot mark it const nor do I know how to initialize it. It’s just a lookup dictionary. In worst case I could convert it from a TMap to a TArray and cast the enum to int32 (blueprints do not support uint8) all the time but this is kinda bad. A last resort would be to store it inside a singleton I guess.

Also I hope that it won’t be garbage collected because I cannot mark it as a UPROPERTY.

I got it to work by using a static function as the ‘initializer’. Feels like a dirty workaround but until someone can give me something better it at least seems to work so far. I’m still not 100% sure though if it gets garbage collected but it’s still not collected after 5 minutes so that is good:

// CPP
TMap<EStructureCategory, FWBList> ABaseStructure::WBMap = ABaseStructure::InitWB();

// The static function
TMap<EStructureCategory, FWBList> ABaseStructure::InitWB()
{
	TMap<EStructureCategory, FWBList> retVal;

	retVal.Add(...)
	retVal.Add(...)
	retVal.Add(...)
    // Etc.

	return retVal;
}

Thanks for this. It’s strange that TArray can be initialized as desired by TMap can’t.

This snippet compiled for me. Will report back if it works in real-time.

static TMap<FString, int32> TestVar = {
	{"5", 5},
	{"3", 3}
};

Update 1

  1. has made a [nice wiki-post][1] for this.
  2. My previous snippet seemed to somehow work.

**Full code**

Header file:

UCLASS(Abstract, Blueprintable)
class PROT_API AYourClass: public AActor
{
	GENERATED_BODY()
	
public:	
	AYourClass();

protected:
	static const TMap<FString, int32> TestVar;
};

Source file:

const TMap<FString, int32> AYourClass::TestVar = {
  {"5", 5},
  {"3", 3}
};

AYourClass::AYourClass()
{
	bAutoDestroyWhenFinished = true;

	for (const auto& Entry : TestVar)
	{
		UE_LOG(LogTemp, Warning, TEXT("-- %d"), Entry.Value);
	}
}

282251-capture.png


**Update 2**
I do understand it is not exactly what question is about yet it might help other people.
3 Likes

That correct, TMap in reality is TPair container so you need to use TPair initializes

@anonymous_user_f5a50610, sounds like std::map then. Thank you for clarification.