gpt4 book ai didi

c++ - 确定函数返回类型的最简单方法

转载 作者:IT老高 更新时间:2023-10-28 13:58:12 27 4
gpt4 key购买 nike

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

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

// using ReturnTypeOfFoo = ???

在编译时确定函数的返回类型(ReturnTypeOfFoo,在本例中为:int)最简单简洁的方法是什么不重复函数的参数类型(仅按名称,因为已知该函数没有任何额外的重载)?

最佳答案

您可以利用 std::function这里将为您提供函数返回类型的别名。这确实需要 C++17 支持,因为它依赖于 class template argument deduction ,但它适用于任何可调用类型:

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

我们可以让它更通用一点

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)>;

关于c++ - 确定函数返回类型的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com