简体   繁体   中英

(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.

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

You can define (and initialise) your lambda in your header file if you compile for C++17 and declare it inline .

At least, I think it works for lambdas, try it.

Lambdas can be stored in function pointers without too much effort like that:

In header: double (*lambda)(double);

In the .cpp file: lambda = [&](double a) { return 2*a; }; lambda = [&](double a) { return 2*a; };

The trouble with this approach is that the defined type of lambda cannot be dynamic. What I mean by that is the assigned lambda needs to match the type defined in the header, so it must have the same return type and, type-wise, exactly the same list of arguments.

And one more little thing. In C++ you are not allowed to re-declare neither functions nor variables in the same scope. If you define a variable directly in a header file and happen to include it into more than one source file, you will get an unpleasant surprise in form of crazy errors. In a header file, define your variable using extern and then define it normally in ONE source file in order to avoid trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM