Search code examples
c++classobjectc++11unreal-engine4

Is there a way to avoid casting for class and/or validity before using an object?


I started programming on UE4 recently and find myself using this code a lot:

if (GetController())
{
    GetController()->GetPlayerState();
}

... or

if (GetController<APlayerController>())
{
    GetController<APlayerController>()->GetMousePosition();
}

The first would check if the actor has a controller and would then return its player state object.

The second would check if the actor has a controller and if that controller is the APlayerController class, then calls a function from the APlayerController class if it is. I feel like there should be a way to avoid doing this every time I want to check if an object exists or if an object is a specific class. Is there?


Solution

  • You can avoid writing the name of the function out twice by declaring a variable in the if statement:

    // "auto"/"auto&"/"auto&&" if not a pointer type
    if (auto* controller = GetController<APlayerController>()) {
        controller->GetMousePosition();
    }