Search code examples
c++unreal-engine4

(UE4) Save a lambda function in the header


i am currently defining a lamda function which i want to save in my header file.

void FURealisticGraspingEditorModule::OnPreviewCreation(const TSharedRef<IPersonaPreviewScene>& InPreviewScene)
{
    TSharedRef<IPersonaToolkit> PersonaToolKitRef = InPreviewScene.Get().GetPersonaToolkit();
    auto lambda = [PersonaToolKitRef]() { return PersonaToolKitRef.Get(); };
    DebugMeshComponent = PersonaToolKitRef.Get().GetPreviewMeshComponent();
}

The lamda variable should get saved in the header. I did not manage to do this yet and now i am curious if this is even possible. I tried auto and TFunctionRef. Maybe there is a hint you guys can give me to achive this or even another way to save this call in a variable.


Solution

  • In order to declare a lambda variable separately from initialising it you need to store it in std::function. The type of a lambda is only known at the point you create it so its not possible to declare a variable to store it separately.

    For example:

    auto a = []{ return 1; }; // OK
    
    auto b; // invalid, can't declare as auto as the type can't be deduced
    b = []{ return 1; };
    
    std::function< bool() > c;
    c = []{ return 1; }; // OK, we can store a lambda in std::function