给定一个非常简单但冗长的函数,例如:
int foo(int a, int b, int c, int d) {
return 1;
}
// using ReturnTypeOfFoo = ???
确定函数返回类型的最简单和简洁的方法是什么(ReturnTypeOfFoo
,在此示例中:int
) 在编译时不重复函数的参数类型(仅通过名称,因为已知该函数没有任何额外的重载)?
您可以利用std::function这里将为您提供函数返回类型的别名。这确实需要 C++17 支持,因为它依赖于类模板参数推导,但它适用于任何可调用类型:
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)>;
此技术仅在函数未重载或函数没有多个的情况下才有效operator()
的定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)