Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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{};
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading