推导独立函数的返回类型 [英] Deducing the return type of a standalone function

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

问题描述

我试图找出非成员函数的返回类型。我首先认为 std :: result_of 执行作业,但是它看起来后者仅适用于可调用对象。特别是 std :: result_of< decltype(f)> :: type 无法运作。我终于设法想出一些工作的代码

I am trying to find out the return type of a non-member function. I first thought that std::result_of does the job, but it looks that the latter works only for callable objects. In particular, std::result_of<decltype(f)>::type is not working. I finally managed to come up with some code that works

#include <iostream>
#include <typeinfo>

void f(int); // we deduce the returning type of this function

template<typename Ret, typename... Args>
struct Helper
{
    using type = Ret;
};

template<typename Ret, typename... Args>
Helper<Ret, Args...> invoke(Ret(*fp)(Args...))
{
    return {};
}

template<typename Ret, typename... Args>
using Return_Type = typename Helper<Ret, Args...>::type;

int main()
{
    std::cout << typeid(decltype(invoke(f))::type).name() << std::endl; // fine
}



我在这里使用一个额外的函数,模板 invoke ,它接受一个指向要推导返回类型的函数的指针,并返回一个helper结构,从中读取实际的返回类型。

I use an additional function here, the template invoke, which takes a pointer to the function I want to deduce the return type, and returns a "helper" structure, from which I read the actual return type.

代码似乎有点复杂,因为它涉及调用函数(虽然没有执行实际的求值)。

The code seems a bit convoluted, since it involves an invoking function (although no actual evaluation is being performed). Is there any other alternative simpler and clearer/shorter way of doing this?

推荐答案

咨询我自己的博客发布,我发现:

Consulting my own old blog posting about this, I found:

template< class Func >
struct ResultOf
{
    typedef typename std::function<
        typename std::remove_pointer<Func>::type
        >::result_type T;
};

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

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