Reputation: 1151
I have a wrapper function similar to the following:
template<typename Func, typename ... Args>
void func(Func f, Args ... args) {
...
f(args...);
...
}
Is it possible to extract the return type from the type Func
at compile time?
For example, a user has the code and calls func
in the following manner:
template<typename T>
T add(const T& l, const T& r) {
return l + r;
}
int main(int argc, char** argv) {
double a = 4.5, b = 5.5;
func(add<double>, a, b);
return 0;
}
Can we infer in the invocation of func
that a function was passed to it which returns a double
? I would like to use the return type information for other things inside func
.
Upvotes: 1
Views: 2663
Reputation: 70843
Since c++17 it's std::invoke_result
:
using result_type = typename std::invoke_result_t<Func(Args...)>;
Upvotes: 2
Reputation: 4367
If you have access to C++14, or just out of curiosity, try not to commit to a particular type. The following code uses a generic lambda and the type is deduced for you. In many cases I find it much easier to work with.
#include <iostream>
using namespace std;
template<typename Func, typename ... Args>
void func(Func&& f, Args ... args) {
return;
}
auto add = [](auto l, auto r) { return l * r; };
int main()
{
auto a = double{4.5};
auto b = double{5.5};
func(add, a, b);
return 0;
}
Ideone: http://ideone.com/wXnc0g
Upvotes: 0
Reputation: 109279
Either of the following should work
using result_type = decltype(std::declval<Func>()(std::declval<Args>()...));
or
using result_type = typename std::result_of<Func(Args...)>::type;
Upvotes: 6