How to get return type of class method?

116 Views Asked by At

I tried to use std::result_of, but could not manage it.

#include <type_traits>

class Foo
{
public:
    int foo();
};

int main() 
{
    using return_type = std::result_of_t<Foo::foo()>; // error
    return 0;
}

So how can I get the return type of Foo::foo?

2

There are 2 best solutions below

0
273K On

Foo::foo() is not a type, std::result_of expects a function type.

#include <type_traits>

class Foo
{
 public:
  int foo();
};

int main() {
  using return_type = std::result_of<decltype(&Foo::foo)>;
  return 0;
}
0
JeJo On

How can I get the return type of Foo::foo?

You can use std::invoke_result as follows.

#include <type_traits>      // std::invoke_result_t

using return_type = std::invoke_result_t<decltype(&Foo::foo), Foo>;

See a demo in godbolt.org

Or using std::declval

#include <utility>     // std::declval

using return_type = decltype(std::declval<Foo>().foo());

See a demo in godbolt.org


Side note: The std::result_of_t is deprecated in and removed in . Therefore, your code bases have to update/ change, when you upgrade to C++20 in the future, in case you use it. Read more:

What is the reason for `std::result_of` deprecated in C++17?