Is it possible to use a UClass as a TMap key?

ArcticKiwi
Tue, 17 May 2016 18:21:45 +0000
C++

Hello !

I find myself with several cases where I want to have a collection of UObject*, created via a collection of TSubclassOf so that it’s data driven ( using Properties )
It works well with a TArray.

My issue is that to access an UObject of a particular subclass I need to iterate over the vector, like it’s done for components, and test IsA(). I would prefer an more direct access with a hash map, as accessing an object by class is what i need 90% of the time.

Here is an example of what i’ve tried.

.h

TMap<TSubclassOf<class UState>, UState*> StatesMap; ( also tried TMap<UClass*, UState*> )

.cpp

// creation, object are added to the map at some point
StatesMap.Add(state->GetClass(), state);

// Access
// stateID here is often something like myState::StaticClass()
UState* UStateManager::GetState(const TSubclassOf<class UState>& stateID)
{
	if (StatesMap.Contains(stateID))
	{
		return StatesMap[stateID];
	}
	return nullptr;
}

Contains never returns true.
TSubclassOf has operators to be converted to and from an UClass*, so i think it’s ok on that front.

I also noticed that if I have a MyState state, then state->GetClass() == MyState::StaticClass() always return false which can be the issue.

So what can I change/add to make it work ?

Do I need to override the == operator for UClass* and the ToHash(UClass*) method ? ( could not remember the exact name )

Thanks !

AKiwi.

4 posts - 1 participant