c++c++11templatestemplate-classes

How to obtain the return type of a function passed into a templated function or class?


How does one obtain the return type of a function (passed into a higher-order function/class) in this fashion:

template <typename F>
auto DoSomething(F&& func) -> /* whatever type func returns */
{
    // whatever...
    return /* something that is func's type */
}

Edit: especially if func required parameters of type T.

My hunch is that decltype or declval ought to be in the picture, but I have had no luck tinkering with it so far.

More thorough context:

struct Poop
{
    float x;
    int y;
}

Poop Digest(float a)
{
    Poop myPoop{ a, 42 };
    return myPoop;
}

template <typename F, typename T>
auto DoSomething(F&& func, T number) -> /* should be of type Poop  */
{
    // whatever... Digest(number)... whatever...
    return /* a Poop object */
}

int main()
{
    Poop smellyThing;
    smellyThing = DoSomething(Digest, 3.4f); // will work
}

Solution

  • Indeed, you can use decltype like this:

    template <typename F, typename T>
    auto DoSomething(F&& func, T number) -> decltype(func(number))
    {
      // ...
      return {};
    } 
    

    Here's a demo.