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?
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, "!");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With