Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the result type of a function in c++11

Consider the following function in C++11:

template<class Function, class... Args, typename ReturnType = /*SOMETHING*/> 
inline ReturnType apply(Function&& f, const Args&... args);

I want ReturnType to be equal to the result type of f(args...) What do I have to write instead of /*SOMETHING*/ ?

like image 907
Vincent Avatar asked Dec 01 '22 20:12

Vincent


2 Answers

I think you should rewrite your function template using trailing-return-type as:

template<class Function, class... Args> 
inline auto apply(Function&& f, const Args&... args) -> decltype(f(args...))
{
    typedef decltype(f(args...)) ReturnType;

    //your code; you can use the above typedef.
}

Note that if you pass args as Args&&... instead of const Args&..., then it is better to use std::forward in f as:

decltype(f(std::forward<Args>(args)...))

When you use const Args&..., then std::forward doesn't make much sense (at least to me).

It is better to pass args as Args&&... called universal-reference and use std::forward with it.

like image 181
Nawaz Avatar answered Dec 04 '22 10:12

Nawaz


It doesn't need to be a template parameter, since it isn't used for overload resolution. Try

template<class Function, class... Args> 
inline auto apply(Function&& f, const Args&... args) -> decltype(f(std::forward<const Args &>(args)...));
like image 33
Ben Voigt Avatar answered Dec 04 '22 08:12

Ben Voigt