我不明白为什么不能使用 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/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: 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 en.cppreference/w/cpp/utility/functional/reference_wrapper
so why isn't v[0] implicitly converted to a reference? In other situations, such as 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
发布评论