Is there a way to avoid duplication and improve readability on template functions return type ?
Here is an example
template <typename FunctionType>
std::enable_if_t<
!std::is_void_v<std::invoke_result_t<FunctionType, MyClass*>>,
std::optional<std::invoke_result_t<FunctionType, MyClass*>>
> CallIfValid(MyClass* instance, FunctionType func)
{
using InvocationType = std::invoke_result_t<FunctionType, MyClass*>;
if (instance != nullptr)
{
return func(instance);
}
else
{
return std::optional<InvocationType>();
}
}
Notice how std::invoke_result_t<FunctionType, MyClass*> ends up duplicated twice in return type, and also a third time in method body.
Any suggestions or trick I am not seeing here ?
Thanks
I have the same problem. In my personal opinion there isn't a good real solution, not for the general case. But there are some mitigations/workarounds you can employ. In your example you can add a default template parameter. Also since you specified the return type, you don't need to repeat the type in the return expression:
template <typename FunctionType, class InvocationType = std::invoke_result_t<FunctionType, MyClass*>>
std::enable_if_t<
!std::is_void_v<InvocationType >,
std::optional<InvocationType >
> CallIfValid(MyClass* instance, FunctionType func)
{
if (instance != nullptr)
{
return func(instance);
}
else
{
return std::nullopt; // if you want to be explicit (I personally prefer this)
// return {}; // if you want to be terse
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With