I was following a network code tutorial and noticed the bloat of functions having to be created due to the way Unreal requires additional functions for RPC calls, e.g.:
.h
void Jump();
UFUNCTION(Server, WithValidation, Reliable)
void ServerJump();
void ServerJump_Implementation() { Jump(); }
bool ServerJump_Validate() { return true; }
.cpp
void MyPawn::Jump()
{
if (Role < ROLE_Authority) { ServerJump(); return; }
// Otherwise handle jump as server.
}
Notice how the Jump() function calls ServerJump() which itself calls Jump(), but as the server. Seeing as how this was a repeating pattern I tried to abstract it out to a general solution:
.h
UFUNCTION(Server, WithValidation, Reliable)
template <typename Class, typename Ret, typename...Types>
Ret ServerCall(Class* Instigator, Ret(Class::*DelegatedFunc)(Types...), Types&&...Params);
template <typename Class, typename Ret, typename...Types>
Ret ServerCall_Implementation(Class* Instigator, Ret(Class::*DelegatedFunc)(Types...), Types&&...Params)
{
return (Instigator->*DelegatedFunc)(std::forward<Types>(Params)...);
}
template <typename Class, typename Ret, typename...Types>
bool ServerCall_Validate(Class* Instigator, Ret(Class::*DelegatedFunc)(Types...), Types&&...Params)
{
return true;
}
Seeing as how I attempted to reduce the problem to something generic, in theory I should just have to call this function anytime I want the above set of procedures to occur; call action, check if server, if not call on server version:
.cpp
void MyPawn::Jump()
{
if (Role < ROLE_Authority) ServerCall(this, &MyPawn::Jump);
// Handle jump as server.
}
Should be able to re-use ServerCall(...) with swimming, moving, speaking, etc without having to create extra server versions of everything. Can even pass as many parameters as I like due to variadic template.
Now while it seems simple enough I keep getting various errors that I can’t make sense of; the most recent is unrecognised type ‘template’.
Is there anything obvious that I’ve missed? I understand the code could probably be more efficient, but I’m surprised that it doesn’t even run.
Edit: The generic templates are all in the header for ‘MyPawn’ as I’m not sure where to keep them as I keep getting various errors depending on where I put them. Ideally they would be in their own source file such as ‘NetworkHelpers.cpp’, but when I attempted that I believe I got an unresolved external symbol error or some such.