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!
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.
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