Templates in C++

From Epic Wiki
Jump to: navigation, search


Author: Rama (talk)

In C++, template classes and functions are a powerful and versatile tool but can be a bit daunting to understand at first. For short functions and classes, using FORCEINLINE can be a great optimization. Look up "c++ inline functions" for a deeper insight on the topic.

The basic pattern is as follows:

template <typename YourTemplateType>
FORCEINLINE void YourFunction()
    // function body

typename may also be replaced with class depending on your use of the templated function.

Example: Spawn Actor From Blueprint

I wrote a templated SpawnBP function to simplify and streamline the process of spawning actors from a blueprint!

template <typename VictoryObjType>
static FORCEINLINE VictoryObjType* SpawnBP(
	UWorld*         TheWorld, 
	UClass*         TheBP,
	const FVector&  Loc,
	const FRotator& Rot,
	const bool      bNoCollisionFail = true,
	AActor*         Owner            = NULL,
	APawn*          Instigator       = NULL
) {
	if(!TheWorld) return NULL;
	if(!TheBP) return NULL;
	FActorSpawnParameters SpawnInfo;
	SpawnInfo.bNoCollisionFail   = bNoCollisionFail;
	SpawnInfo.Owner              = Owner;
	SpawnInfo.Instigator         = Instigator;
	SpawnInfo.bDeferConstruction = false;
	return TheWorld->SpawnActor<VictoryObjType>(TheBP, Loc, Rot, SpawnInfo);

Notice it is possible to return a pointer of the template type!

Calling SpawnBP Function

From a Static Library, in an actor class (for use of GetWorld()). SpawnLoc and SpawnRot are calculated by you based on your needs.

AActorBaseClass* NewActor = UFunctionLibrary::SpawnBP<AActorBaseClass>(GetWorld(), TheActorBluePrint, SpawnLoc, SpawnRot);

From an instanced Actor class:

AActorBaseClass* NewActor = SpawnBP<AActorBaseClass>(GetWorld(), TheActorBluePrint, SpawnLoc, SpawnRot);

In-Engine Example: Min/Max of Array

In Unreal Engine Version 4.3, Epic accepted my github pull request functions to determine the minimum / maximum values of an array.

Full code samples can be found here

Rama (talk)