是否可以在不传递参数的情况下获得函数的返回类型? [英] Is it possible to get the return type of a function without passing arguments to it?

查看:59
本文介绍了是否可以在不传递参数的情况下获得函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很显然,您可以使用decltype(foo())获得函数的返回类型,但是如果foo接受了无效的参数,则必须将一些虚拟参数传递给foo才能使其正常工作.但是,有没有一种方法可以获取函数的返回类型而不必传递任何参数呢?

Obviously, you can get the return type of a function with decltype(foo()), but if foo takes arguments that won't work, you'd have to pass some dummy arguments to foo in order for it to work. But, is there a way to get the return type of a function without having to pass it any arguments?

推荐答案

假定返回类型不取决于参数类型(在这种情况下,您应该使用 std :: result_of 之类的东西,但是您必须提供这些参数的类型),您可以编写一个简单的类型特征,让您从函数类型中推断出返回类型:

Supposing the return type does not depend on the argument type (in which case you should use something like std::result_of, but you would have to provide the type of those arguments), you can write a simple type trait that lets you deduce the return type from the function type:

#include <type_traits>

template<typename T>
struct return_type;

template<typename R, typename... Args>
struct return_type<R(Args...)>
{
    using type = R;
};

int foo(double, int);

int main()
{
    using return_of_foo = return_type<decltype(foo)>::type;
    static_assert(std::is_same<return_of_foo, int>::value, "!");
}

这篇关于是否可以在不传递参数的情况下获得函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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