Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 698
NeomerArcana Avatar asked Dec 31 '16 10:12

NeomerArcana


People also ask

How do I get the return type of a function in C++?

To get the return type of foo , we simply use the following: using t = decltype(foo()); t now contains the return type.

What happens when a function is defined as a template?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

Can templates be used for functions?

Templates are powerful features of C++ which allows us to write generic programs. We can create a single function to work with different data types by using a template.


1 Answers

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;
like image 87
Jarod42 Avatar answered Oct 07 '22 08:10

Jarod42