Templates in C++

Overview Author: () 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...

Updated over 1 year ago Edit Page Revisions

Overview

Author: ()

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 
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 
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(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(GetWorld(), TheActorBluePrint, SpawnLoc, SpawnRot);

From an instanced Actor class:

AActorBaseClass* NewActor = SpawnBP(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

()

Blueprint Templates

Template like functionality can be developed for a UFUNCTION using a combination of DeterminesOutputType and DynamicOutputParam.

Ex.

	UFUNCTION(BlueprintCallable, Category="Utilities",  meta=(WorldContext="WorldContextObject", DeterminesOutputType="ActorClass", DynamicOutputParam="OutActors"))
        static void GetAllActorsOfClass(const UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, TArray<AActor*>& OutActors);

In the function (GetAllActorsOfClass), the type of output (OutActors) depends on the type of class (ActorClass) provided.