Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining return type of std::function

I'm writing a template function that receives a std::function object (Generated by calling std::bind with the proper arguments). Within this function, I would like to determine the return type of this function object. Is is possible?

As a matter of fact, I want the template function to return the same type. Can you think of an elegant, standard based, way of achieving this goal?

Something like:

template <typename T>
T::return_type functionObjWrapper(T functionObject) {
   // ...
   return functionObject();
}

Thanks

like image 686
Mr. Anderson Avatar asked Jun 10 '15 12:06

Mr. Anderson


2 Answers

You can do it using decltype and trailing return type:

template <typename T>
auto functionObjWrapper(T functionObject) -> decltype(functionObject()) {
   // ...
   return functionObject();
}
like image 196
Some programmer dude Avatar answered Sep 26 '22 08:09

Some programmer dude


You're looking for std::function<F>::result_type

I.e.

template <typename F>
typename std::function<F>::result_type
functionObjWrapper(std::function<F> functionObject) {
   // ...
   return functionObject();
}

The typename before std::function<F>::result_type is needed because that's a dependent type name.

like image 43
MSalters Avatar answered Sep 24 '22 08:09

MSalters