类型模拟一个C ++引用比std :: reference

编程入门 行业动态 更新时间:2024-10-25 19:22:20
本文介绍了类型模拟一个C ++引用比std :: reference_wrapper更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我设计一个类似于C ++引用的类,但是有一些额外的工具(bookkeeping)。

I am designing a class that behaves like a C++ references but does some extra instrumental stuff (bookkeeping).

最初我认为 std :: reference_wrapper< T> 将是一个很好的模型。但是一段时间后,我意识到 std :: reference_wrapper< T> 不起作用,即使在原则上作为C ++引用,因为赋值重新绑定内部指针。 >

Initially I thought that std::reference_wrapper<T> would be a good model. But after a while I realized that std::reference_wrapper<T> doesn't behave, even in principle, as a C++ reference because assignment rebinds the internal pointer.

double a = 5.; double b = 3.; double& ref = a; ref = b; assert(&ref != &b); // ref is not bound to b std::reference_wrapper<double> refwpr = a; refwpr = b; assert(&refwpr.get() == &b); // ref wrapper was rebound to b

我当然可以改变我自己的类的行为重新绑定),但我认为也许一个类模拟引用已经在那里。例如 std :: real_reference< T> 。

我认为它也可以是有用的,例如在许多地方一看到 std :: vector< std :: reference_wrapper< T>> 作为 std :: vector< T&> 但是这是误导,因为语义是不同的,但是可以通过一些修改 std :: vector< std :: real_reference< T>< / code>

I think it can be useful too, for example in many places one sees std::vector<std::reference_wrapper<T>> presented as an alternative to std::vector<T&> but this is misleading because the semantics is different but could be achieved with some modifications std::vector<std::real_reference<T>>.

推荐答案

template <typename T> class Tref { std::tuple<T &> t; public: template <typename... Args> Tref(Args&&... args): t(std::forward<Args>(args)...) {} operator T &() { return std::get<0>(t); } decltype(&std::get<0>(t)) operator&() { return &std::get<0>(t); } }; Tref<double &> t(a); t = b; assert(&t != &b);

std :: reference_wrapper 当模板擦除引用时。你不需要构建一个类来满足你的需要,只需使用正常的引用。 (我可能不清楚,我的英语不好。)

What std::reference_wrapper does is binding when the template erase the reference. You needn't build a class to meet your needs, and just use normal reference. (I may not describe clearly. My English is poor.)

更多推荐

类型模拟一个C ++引用比std :: reference

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

发布评论

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

>www.elefans.com

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