为什么std :: reference

编程入门 行业动态 更新时间:2024-10-25 03:19:41
本文介绍了为什么std :: reference_wrapper在调用成员函数时隐式转换为引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不明白为什么不能使用 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:

#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 en.cppreference/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

本文发布于:2023-08-04 17:31:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!