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

问题描述

给出一个非常简单但冗长的函数,例如:

Given a very simple, but lengthy function, such as:

int foo(int a, int b, int c, int d) {
    return 1;
}

// using ReturnTypeOfFoo = ???

确定函数返回类型的最简单明了的方法是什么( ReturnTypeOfFoo ,在此示例中: int )在编译时,而无需重复函数的参数类型(仅按名称,因为已知该函数没有任何其他重载)?

What is the most simple and concise way to determine the function's return type (ReturnTypeOfFoo, in this example: int) at compile time without repeating the function's parameter types (by name only, since it is known that the function does not have any additional overloads)?

推荐答案

您可以利用此处将为您提供函数返回类型的别名。这确实需要C ++ 17支持,因为它依赖于类模板参数推导,但可用于任何可调用类型:

You can leverage std::function here which will give you an alias for the functions return type. This does require C++17 support, since it relies on class template argument deduction, but it will work with any callable type:

using ReturnTypeOfFoo = decltype(std::function{foo})::result_type;






我们可以使它更通用一些,例如


We can make this a little more generic like

template<typename Callable>
using return_type_of_t =
    typename decltype(std::function{std::declval<Callable>()})::result_type;

然后您就可以使用它了

int foo(int a, int b, int c, int d) {
    return 1;
}

auto bar = [](){ return 1; };

struct baz_
{
    double operator()(){ return 0; }
} baz;

using ReturnTypeOfFoo = return_type_of_t<decltype(foo)>;
using ReturnTypeOfBar = return_type_of_t<decltype(bar)>;
using ReturnTypeOfBaz = return_type_of_t<decltype(baz)>;

这篇关于确定函数返回类型的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:45