[英]std::result_of for lvalue/rvalue arguments
I noticed this behavior of std::result_of
when playing around: 我在玩耍时注意到了
std::result_of
这种行为:
struct Foo {
int operator()(const int&) const { ... }
char operator()(int&&) const { ... }
};
result_of_t<Foo(const int&)> a; // int
result_of_t<Foo(int&&)> b; // char
result_of_t<Foo(int)> c; // char -- why?
Why does std::result_of
prefer the function taking an rvalue reference for the third case? 为什么
std::result_of
在第三种情况下更喜欢采用右值引用的函数?
std::result_of
when given non-reference parameters presumes they are rvalues. 当给定的非参考参数假定它们是右值时,
std::result_of
。
In fact, std::result_of_t<A(B)>
is the same as std::result_of_t<A(B&&)>
in almost all cases. 实际上,
std::result_of_t<A(B)>
是相同std::result_of_t<A(B&&)>
在几乎所有情况下。
You can see some possibile implementations here if you want to see why. 如果您想了解原因,则可以在此处看到一些可能的实现 。 Basically,
result_of_t<A(B)>
does a decltype( std::declval<A>()(std::declval<B>()) )
(ignoring member function pointer cases), and a B&&
rvalue reference and a temporary B
will invoke the same overloads of any operator()
on an A
. 基本上,
result_of_t<A(B)>
进行decltype( std::declval<A>()(std::declval<B>()) )
(忽略成员函数指针的情况),以及B&&
rvalue引用和临时B
将调用与A
上任何operator()
相同的重载。
There are three primary value categories (lvalue, prvalue and xvalue), and three reference qualifiers (none, &
and &&
). 共有三个主要值类别 (lvalue,prvalue和xvalue)和三个参考限定符 (none,
&
和&&
)。
Clearly it makes sense that &
should designate lvalue category and &&
should designate xvalue; 显然,
&
应该指定左值类别, &&
应该指定xvalue有意义。 it follows that an omitted reference qualifier should designate prvalue. 因此,省略的参考限定符应指定prvalue。
Note that this is the same as you would get for a function with the corresponding return type: 请注意,这与具有相应返回类型的函数所获得的相同:
int f(); // returns prvalue int
int& f(); // returns lvalue reference to int
int&& f(); // returns xvalue reference to int
And in your case: 在您的情况下:
const int& f();
int&& g();
int h();
decltype(Foo{}(f())) a; // int
decltype(Foo{}(g())) b; // char
decltype(Foo{}(h())) c; // char
So you can see that result_of
is just showing what decltype
would tell you. 因此,您可以看到
result_of
只是显示了decltype
会告诉您什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.