I’m wrapping a collection of boiler plated Async code snippets to learn more about macros & templating in Unreal Engine 5.3, C++ 17. Unfortunately my C++ capabilities are quite limited and just don’t understand enough about the complexities of using templates and macros together. (The below example is only a 1 liner, but for more complex implementations should I even be using macros..?)
From what I can see i would only need to include the type declaration when calling the BlockingTask
method but don’t know how to pass that information through a macro.
How should I handle the macro/template syntax in order to fix the erroring lambda version?
Other.cpp
void TestSyntax(){
//Preferred syntax, Argument Error lambda[]() -> FString
FString strA = ASYNC_BLOCKING_TASK_A([&]() { return Async_TestB(); });
/* The rest all Work */
//Verifying the template works when passing the type
FString strB = ::Async::BlockingTask<FString>([&]() { return Async_TestB(); });
//The macro works when passing the method as a variable.
//I'd prefer to not have to manually declare the task though.
TFunction<FString()> task_B = [this]() { return this->Async_TestB(); };
FString strC = ASYNC_BLOCKING_TASK_B(task_B);
FString strD = ::Async::BlockingTask(task_B);
}
Macros.h
#define ASYNC_BLOCKING_TASK_A(method)
{
::Async::BlockingTask(method);
}
#define ASYNC_BLOCKING_TASK_B(method)
::Async::BlockingTask(method);
namespace Async{
template<typename T>
T BlockingTask(TFunction<T()> method) {
TFuture<T> result = AsyncThread(method);
return result.Get();
}
}
Please ignore the terrible concept of a task that blocks the calling thread. I started by templating the most basic implementation to reduce complexity while learning. I have ‘good’ implementations that support cancellation tokens and completion callbacks that i plan to create templated macros for once I understand how to do it correctly.