C++ template function deducing return type

I’m trying to create a simple template function which takes a callable object and a couple of int values, and returns the result of invoking the callable with those values.

How do I get the function to figure out the return value’s type, and also be able to create such a type with its default value. This works:

template <typename Func>
auto CallFunc(Func f, int a, int b) -> std::invoke_result_t<Func, int, int>
{
    using return_type = std::invoke_result_t<Func, int, int>;

    if (a > 0) {
        return (f)(a, b);
    }

    return return_type{};
}

See here for a demo.

It does feel a little ugly though, and having to deduce it twice like that isn’t great.

Is there a simpler way to achieve this? Despite this code working I can’t help but feel as though I’ve taken a wrong turn somewhere!

>Solution :

Is there a simpler way to achieve this?

Simply use decltype here

template <typename Func>
auto CallFunc(Func f, int a, int b) -> decltype(f(a, b))
//                                     ^^^^^^^^^^^^^^^^^^   
{
    using return_type = decltype(f(a, b));
    //                  ^^^^^^^^^^^^^^^^^^

    // ... code    
    return return_type{};
}

Leave a Reply