为什么std :: reference_wrapper在调用成员函数时隐式转换为引用? [英] Why doesn't std::reference_wrapper implicitly cast to a reference when calling member function?
问题描述
我不明白为什么不能使用 std :: reference_wrapper
这样:
#include< vector>
#include< functional>
struct Foo
{
void f(){};
};
int main()
{
std :: vector< std :: reference_wrapper< Foo> vrFoo;
Foo foo;
vrFoo.push_back(foo);
// vrFoo [0] .f(); // error
vrFoo [0] .get()。f(); //或static_cast< Foo&>(v [0])。
}
为什么我们必须使用 get
成员函数?它看起来像 std :: reference_wrapper
隐式转换为 T&
通过 ()const noexcept
,请参阅 http:// en。 cppreference.com/w/cpp/utility/functional/reference_wrapper
那么为什么 v [0]
隐式转换为引用? / p>
在其他情况下,例如
std :: cout< < v [0]<< std :: endl
此转换发生(我假设 Foo
overloads operator
因为。
始终用于访问其应用的对象的成员。不会考虑类型转换。
有一个 proposal 允许运算符重载
,以完全满足您的要求,但这将不是标准,直到至少C ++ 17,如果有的话。
I don't understand exactly why one cannot use a std::reference_wrapper
like this:
#include <vector>
#include <functional>
struct Foo
{
void f() {};
};
int main()
{
std::vector<std::reference_wrapper<Foo>> vrFoo;
Foo foo;
vrFoo.push_back(foo);
// vrFoo[0].f(); // error
vrFoo[0].get().f(); // or static_cast<Foo&>(v[0]).f();
}
Why do we have to use the get()
member function? It looks like std::reference_wrapper
has an implicit conversion to T&
via operator T&() const noexcept
, see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
so why isn't v[0]
implicitly converted to a reference?
In other situations, such as
std::cout << v[0] << std::endl
this conversion takes place (I assume here that Foo
overloads operator<<
)
Because .
is always used to access members of the object it's applied to. Type conversions aren't considered.
There's a proposal to allow overloading of operator.
, to enable exactly what you want, but that won't be standard until at least C++17, if at all.
这篇关于为什么std :: reference_wrapper在调用成员函数时隐式转换为引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!