获取模板中的函数返回类型 [英] Get function return type in template

查看:156
本文介绍了获取模板中的函数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取传递给模板的任何函数的返回类型?

我不知道如何在 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.

这篇关于获取模板中的函数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆