Reputation: 527
Obviously, you can get the return type of a function with decltype(foo()), but if foo takes arguments that won't work, you'd have to pass some dummy arguments to foo in order for it to work. But, is there a way to get the return type of a function without having to pass it any arguments?
Upvotes: 4
Views: 1076
Reputation: 3560
C++11 provides std::result_of
.
http://en.cppreference.com/w/cpp/types/result_of
In the case where the function takes arguments, you can provide "dummy" arguments with std::declval
.
http://en.cppreference.com/w/cpp/utility/declval
Upvotes: 7
Reputation: 126412
Supposing the return type does not depend on the argument type (in which case you should use something like std::result_of
, but you would have to provide the type of those arguments), you can write a simple type trait that lets you deduce the return type from the function type:
#include <type_traits>
template<typename T>
struct return_type;
template<typename R, typename... Args>
struct return_type<R(Args...)>
{
using type = R;
};
int foo(double, int);
int main()
{
using return_of_foo = return_type<decltype(foo)>::type;
static_assert(std::is_same<return_of_foo, int>::value, "!");
}
Upvotes: 7