如何使用std::invoke_result_t在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;
}
非常感谢您的帮助!
发布于 2022-08-19 22:21:54
std::invoke_result_t
可以处理类型,但C<int>::Get
不是类型。它是一个非静态的成员函数.
C<int>::Get
的类型是std::vector<int>(C<int>::)()
:C<int>
的成员函数,它返回std::vector<int>
,不接受参数。这种类型就是您需要给std::invoke_result_t
的东西。或者更确切地说,是指向它的指针,因为您不能传递原始成员函数类型。
此外,std::invoke_result_t
将第一个参数类型作为在处理成员函数指针时调用成员函数的对象类型。
因此,你需要:
std::invoke_result_t<std::vector<int>(C<int>::*)(), C<int>>
或者,如果您不想写出整个成员函数类型:
std::invoke_result_t<decltype(&C<int>::Get), C<int>>
void
参数列表等同于C++中的空参数列表。除非您想要与C代码共享函数声明,否则没有理由在void
中显式指定C++参数列表。
https://stackoverflow.com/questions/73422693
复制相似问题