Std :: function return type definition
I am writing a template function that receives an object std::function
(generated by calling std::bind
with appropriate arguments). Inside this function, I would like to define the return type of this function object. Is it possible to?
Actually, I want the template function to return the same type. Can you think of an elegant, standards-based way to achieve this goal?
Something like:
template <typename T>
T::return_type functionObjWrapper(T functionObject) {
// ...
return functionObject();
}
thank
source to share
You are looking for std::function<F>::result_type
those.
template <typename F>
typename std::function<F>::result_type
functionObjWrapper(std::function<F> functionObject) {
// ...
return functionObject();
}
typename
before std::function<F>::result_type
is required because it is the name of the dependent type.
source to share
template <class F>
std::result_of_t<F&()> functionObjWrapper(F functionObject) {
// ...
return functionObject();
}
std::result_of
takes a type expression that "looks like a function call". It then tells you what will happen if you made a function call with this callable type and these arguments.
If you are missing C ++ 14, replace std::result_of_t<?>
with typename std::result_of<?>::type
or write your own:
template<class Sig>
using result_of_t=typename std::result_of<Sig>::type;
In many implementations, C ++ 11 result_of
is even SFINAE friendly.
I do F&()
instead F()
because we will be using a non-const lvalue type to make the call F
. If your last line was std::move(functionObject)()
or std::forward<F>(functionObject)()
, you would result_of_t<F()>
.
source to share