如何获取传递给模板的任何函数的返回类型? 我不知道如何在 template< typename T> 之间进行转换和 template< typename结果,类型名Args ...> :
How can I get return type for any function passed to template? I don't know how to convert between template<typename T> and template<typename Result, typename Args...>:
template<typename T> void print_name(T f) { static_assert(internal::is_function_pointer<T>::value || std::is_member_function_pointer<T>::value, "T must be function or member function pointer."); typename decltype(f(...)) Result; // ??? typename std::result_of<T>()::type Result; // ??? printf("%s\n", typeid(Result).name()); } void f_void() {} int f_int(int x) { return 0; } float f_float(int x, int y) { return 0.f; } struct X { int f(int x, float y) { return 0; } }; int main() { print_name(f_void); print_name(f_int); print_name(f_float); print_name(&X::f); return 0; }如何获取 Result 内部函数 print_name ?
推荐答案正在使用一种可能的解决方案提取返回类型以及所有参数的函数声明。您甚至不必定义它。 它遵循一个最小的有效示例:
A possible solution is using a function declaration that extracts the return type as well as all the parameters. You don't have even to define it. It follows a minimal, working example:
#include<typeinfo> #include<cstdio> template<typename R, typename... A> R ret(R(*)(A...)); template<typename C, typename R, typename... A> R ret(R(C::*)(A...)); template<typename T> void print_name(T f) { printf("%s\n", typeid(decltype(ret(f))).name()); } void f_void() {} int f_int(int x) { return 0; } float f_float(int x, int y) { return 0.f; } struct X { int f(int x, float y) { return 0; } }; int main() { print_name(f_void); print_name(f_int); print_name(f_float); print_name(&X::f); return 0; }如您所见,为 ret提供的声明具有与提交的函数或成员函数相同的返回类型。 其余的 decltype 会
As you can see, the declarations provided for ret has the same return type of the submitted function or member function. A decltype does the rest.
更多推荐
获取模板中的函数返回类型
发布评论