Get function result type 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 be equal to the result type f(args...) What do I need to write instead of /*SOMETHING*/ ?

+4
source share
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 for me).

It is better to pass args as Args&&.. , called the universal link, and use std::forward with it.

+14
source

It does not need to be a template parameter because it is not used to allow overloading. Try

 template<class Function, class... Args> inline auto apply(Function&& f, const Args&... args) -> decltype(f(std::forward<const Args &>(args)...)); 
+4
source

All Articles