Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplication on template function return type?

Tags:

c++

c++17

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

like image 962
teldios Avatar asked Dec 06 '25 15:12

teldios


1 Answers

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
    }
}
like image 126
bolov Avatar answered Dec 09 '25 17:12

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!