Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the return type of a function without passing arguments to it?

Tags:

c++

c++11

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?

like image 337
user467526 Avatar asked Dec 11 '22 14:12

user467526


2 Answers

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, "!");
}
like image 89
Andy Prowl Avatar answered Dec 14 '22 04:12

Andy Prowl


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

like image 28
user2093113 Avatar answered Dec 14 '22 03:12

user2093113