获取模板中的函数返回类型

编程入门 行业动态 更新时间:2024-10-24 08:27:32
本文介绍了获取模板中的函数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何获取传递给模板的任何函数的返回类型? 我不知道如何在 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.

更多推荐

获取模板中的函数返回类型

本文发布于:2023-07-22 10:34:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186737.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模板   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!