代码的目的:我需要能够将任何函数类型作为参数提供给构造函数,以便我可以从该类中调用它。
为什么必须这样?因为我使用虚幻引擎4 FRunnable 线程所做的就是这样线程将调用特定接口(虚拟成员函数)来运行线程的方式,所以除非我想为我想要分配的每个线程任务创建一个新类,否则我必须尝试将其提供给泛型函数以便我可以我的线程类具有最大的功能。
我使用线程类进行什么? SQLite3 查询,每个需要保存数据的查询总是需要不同的参数,而 SELECT 查询。
这是我下面的代码,第一部分工作正常但第二部分构造函数没有;
线程类构造函数
FThreading::FThreading(std::function<void()> funcTask) {
//Check if the Thread has not been defined and that the system supports multi threading
if (!Thread && FPlatformProcess::SupportsMultithreading()) {
//Create our thread
voidNoParaFunc = funcTask;
curFlag = 1;
Thread = FRunnableThread::Create(this, TEXT("FThreading"), 0, TPri_BelowNormal);
} else {
//Can't multithread, call the function straight
funcTask();
}
}
电话:
std::function<void()> passFunc = std::bind(&UCP_GameInstance::InitDB, GameInst);
FThreading* threadPointer = new FThreading(passFunc);
现在这是我需要帮助的代码:
FThreading::FThreading(std::function<bool(FString, FString)> funcTask) {
//Check if the Thread has not been defined and that the system supports multi threading
if (!Thread && FPlatformProcess::SupportsMultithreading()) {
//Create our thread
boolTwoString = funcTask();
curFlag = 2;
Thread = FRunnableThread::Create(this, TEXT("FThreading"), 0, TPri_BelowNormal);
}
else {
//Can't multithread, call the function straight
funcTask();
}
}
电话:
void UCP_GameInstance::AddNewSurvivor(FString First, FString Second, FString Nation, FString Age, FString Blood, FString Level, FString Spec) {
FString Query = "INSERT INTO SurvivorData (First, Second, Nation, Age, Blood, Level, Spec) " +
"VALUES (" + First + ", " + Second + ", " + Nation + ", " + Age + ", " + Blood + ", " + Level + ", " + Spec + ");";
std::function<bool(FString, FString)> passFunc = std::bind(&USQLiteDatabase::ExecSql, GetDBName(), Query);
FThreading* threadPointer = new FThreading(passFunc);
}
任何帮助都会非常感激,因为我已经暂时停留在这个问题上,现在,即使是设计建议/更改也不仅仅是邀请。
感谢您的时间。
答案 0 :(得分:1)
正如您使用std::bind
所发现的那样,您无法真正传递任何随机函数 - FThreading
如何知道如何调用它?有一个实际的调用指令funcTask();
,它立即告诉我们funcTask
没有参数。
现在,在第二次重载中,funcTask
需要两个FString
个参数。显然,这意味着funcTask();
调用是无意义的。它只是缺少两个论点。我们不能为你发明这些论点。
这是标题中的想法的一般问题,&#34;将任何类型的函数作为参数&#34;。它通常会失败,不是因为它无法通过任何功能,而是因为它无法调用该功能。
PS。 boolTwoString = funcTask();
应该只是boolTwoString = funcTask
- 它毕竟不是直接打电话。