我设计一个类似于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
发布评论