Initializing a static TMAP in a Static Library

I am c# developer learning C++ in unreal, and I am trying to figure out how I am supposed to initialize some values into a static TMAP

I tried everything I could think of with nothing but compile errors. So I final settled on something (not really since I am here asking for the correct way to do this).

This is a static TMAP. Initial values will never change. Just using it for looking up values.

So below is the code I got to compile (not tested yet). What I was expecting to do was to declare static TMAP in header and initialize it in either h or cpp. Could not get that to work. Anyone know how?

Thanks!



h file

static int32 GetDegreesFromDirection(EDonjonDirection direction);

cpp file

TMap<EDonjonDirection, int32> DegreesByDirection;

int32 UDonjonUtilityLibrary::GetDegreesFromDirection(EDonjonDirection direction)
{
	if (DegreesByDirection.Num() == 0)
	{
		DegreesByDirection.Add(EDonjonDirection::Up, 1);
               // add other values...
	}

	return DegreesByDirection[direction];
}



What do you mean by a static library? Is this inside a dedicated module? If so, you could initialize the map inside the StartupModule method.

TMap doesn’t seem to provide an initializer list constructor, so there’s no way to declare it const and initialize the entries inline unfortunately.

Question is: why do you need a tmap?
Can’t you do something like:



switch(direction) {
    case EDonjonDirection::Up:
        return 1;
        break;
    ...
}


@snaiperskaya, because switch-case looks ugly, not considering it’s [kind of] O(N) complexity [in the worst case]; map has constant time.
But yes, you can. In fact, it is used in ShooterExample. At least for ImpactFXs.

Not the exact solution for the question but it might help someone: wiki-post by Rama.

switch is implemented by a binary search tree with many entries. with small ranges, it is implemented via jump table

You should add this in cpp file

 TMap&lt;EDonjonDirection, int32&gt; DegreesByDirection = TMap&lt;EDonjonDirection, int32&gt;();

yep, that should cover it. However, there is, as far as I’m aware, no way to fill it statically, you’ll need to fill it at runtime. I think. I could be wrong, though.