关于获取函数结果类型的各种方法 [英] On the various ways of getting the result type of a function
问题描述
在必须推断出函数调用结果类型的情况下,C ++似乎非常乐于帮助我们,提供了(至少据我所知)以下两种解决方案:
-
std :: result_of< F(Args ...)> :: type
-
一种核心语言语法:
decltype(std :: declval< F(>)(std :: declval< Args>()...);
我的问题是,两者之间有何区别吗?
result_of
的返回类型为 std :: invoke
应用于给定类型时-甚至在 invoke $ c $中使用c>的声明的返回类型。但是,
调用
涵盖的场景远远超过普通的非成员函数调用。您显示的 decltype(…)
中的表达式只是 result_of
检查的众多表达式之一。
因此,只有在保证 F
是函数对象类型的情况下,您的选项才等效。否则,在 decltype(…)
不是以下情况的情况下, result_of<…>
可能有效:
结构A {int i;};
decltype(std :: declval< int A :: *>()(std :: declval< A>()))//错误
std :: result_of_t< int A :: *( A)> // = int&& ;,被视为成员访问权限
演示。 (请注意,从C ++ 14开始, result_of
是SFINAE友好的,即无效类型会导致平滑的推导失败,就像 decltype
。)
In a context where the type of the result of a function call must be deduced, C++ seems to be more that happy to help us, providing (at least to my knowledge the following) two solutions :
The result of type trait :
std::result_of<F(Args...)>::type
A core language syntax :
decltype(std::declval<F>()(std::declval<Args>()...);
My question is, are the any differences between the two? Is there a context where one cannot be substituted by the other and if not why did we need a type trait to do something the language could do out of the box ?
result_of
yields the return type of std::invoke
when applied to the given types - it's even used in invoke
's declared return type. However, invoke
covers far more scenarios than just ordinary non-member function calls. The expression in decltype(…)
you showed is just one of many that result_of
examines.
Thus your options are only equivalent if F
is guaranteed to be a function object type. Otherwise result_of<…>
may be valid in cases in which decltype(…)
is not:
struct A {int i;};
decltype(std::declval<int A::*>()(std::declval<A>())) // error
std::result_of_t<int A::*(A)> // = int&&, treated as a member access
Demo. (Note that result_of
is SFINAE friendly as of C++14, i.e. invalid types cause a smooth deduction failure as for decltype
.)
这篇关于关于获取函数结果类型的各种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!