Lambda函数
用变量表示了一个函数(匿名函数)
典型用法
void AMyActor::BeginPlay() {
TArray<AActor*> ArrayForLambdaFunc;
auto lambda = [&ArrayForLambdaFunc](int key) -> int {
for (auto& it : ArrayForLambdaFunc)
GLog->Log("Item: "+ it->GetActorLabel());
return 0;
};
}
中括号[] 常用参数如下
- [] 不捕获任何外部变量
- [=] 所有变量传值
- [&x] 变量x传引用
注意事项
- Lambda函数可以使用this指针,但必须捕获[this]
- 该变量可以用std::function<int()> lambda; 声明
Delegate
用来方便的执行回调函数的一套体系
典型用法
class AMyActor{
GENERATED_BODY()
DECLARE_DELEGATE(MyDelegateSimple);
DECLARE_MULTICAST_DELEGATE(MyDeletageMulti);
UFUNCTION()
void TestFunction1();
UFUNCTION()
void TestFunction2();
}
AMyActor::BeginPlay() {
MyDelegateSimple delegate1;
delegate1.BindUFunction(this, FName("TestFunction1"));
delegate1.Execute(); //run this function.
auto lambda = [](){
//Code in Lambda function;
};
MyDelegateMulti delegate2;
delegate2.AddUFunction(this, FName("TestFunction1"));
delegate2.AddUFunction(this, FName("TestFunction2"));
delegate2.AddLambda(lambda);
delegate2.Broadcast();//Run function in sequence:TextFunction2 -> TestFunction1
}
详细用法
class AMyActor{
//这个Delegate引的function将会返回int
DECLARE_DELEGATE_RetVal(int, DelegateJason);
//这个Delegate引的function(float)将会返回int
DECLARE_DELEGATE_RetVal_OneParam(int, DelegateMou, float);
//这个Delegate引的function(float,float)将会返回int
DECLARE_DELEGATE_RetVal_TwoParams(int, DelegateKevin, float, float);
UFUNCTION()
int JasonSay();
UFUNCTION()
int MouSay(int age);
UFUNCTION()
int KevinSay(float x,float y);
}