c++functionreturn-typec++-templates

How can I retrieve the return type of a function to use in a template?


I have a function somewhere called x that returns a know value and has known parameters:

int x(int y);

I have somewhere else, I want to create a container to contain n invocations of this function. Then I want to execute it that many times.

The problem is, I don't want to rely on it being an int return type. I need to deduce the return type at compile time. Something like:

std::vector<result_of<x(int)>::type> results;

But I don't want to have to specify the parameter values because they're static.


Solution

  • You can create your own traits, something like:

    template <typename F> struct my_result_of;
    
    template <typename F> struct my_result_of<F*> : my_result_of<F> {};
    
    template <typename Ret, typename ... Ts>
    struct my_result_of<Ret(Ts...)>
    {
        using type = Ret;
    };
    
    template <typename F> using my_result_of_t = typename my_result_of<F>::type;
    

    And use it like (assuming no overloads of x):

    std::vector<my_result_of_t<decltype(x)>::type> results;