Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: How can one get return type of a class member function using std::invoke_result_t?

How can one get return type of a class member function using std::invoke_result_t in C++?

#include <type_traits>
#include <vector>

template <class T>
struct C
{
    auto Get(void) const { return std::vector<T>{1,2,3}; }
};

int main(void)
{
 // what should one put below to make x to have type std::vector<int> ?
 std::invoke_result_t<C<int>::Get, void> x;
 //                   ^^^^^^^^^^^^^^^^^
 return 0;
}

Thank you very much for your help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

std::invoke_result_t works on types, but C<int>::Get is not a type. It is a non-static member function.

The type of C<int>::Get is std::vector<int>(C<int>::)(): Member function of C<int> that returns std::vector<int> and accepts no parameters. That type is what you need to give to std::invoke_result_t. Or rather, a pointer to it, since you can’t pass raw member function types around.

Also, std::invoke_result_t treats the first argument type as the type of object on which to call the member function when it’s dealing with pointers to member functions.

Thus you need:

std::invoke_result_t<std::vector<int>(C<int>::*)(), C<int>>

Or, if you don’t want to write out the whole member function type:

std::invoke_result_t<decltype(&C<int>::Get), C<int>>

Demo


Sidenote: void parameter lists are equivalent to empty parameter lists in C++. There’s no reason to explicitly specify a void parameter list in C++ unless you want to share a function declaration with C code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading