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.
To get the return type of foo , we simply use the following: using t = decltype(foo()); t now contains the return type.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With