比 std::reference_wrapper 更好地模拟 C++ 引用的类型

2022-01-05 00:00:00 reference c++ c++11 stl reference-wrapper

我正在设计一个类,它的行为类似于 C++ 引用,但做了一些额外的工具性工作(簿记).

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

最初我认为 std::reference_wrapper 将是一个很好的模型.但过了一段时间我意识到 std::reference_wrapper 的行为,即使在原则上,也不能作为 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".

I can of course change that behavior for my own class (not to rebind) but I though that maybe a class that emulates a reference is already out there. For example something like "std::real_reference<T>".

是否有一个类(标准或非标准)可以更接近地模拟引用?

我认为它也很有用,例如在人们看到的许多地方std::vector<std::reference_wrapper<T>> 作为 std::vector<T&> 的替代方案出现,但这是一种误导,因为语义是不同,但可以通过一些修改来实现std::vector>.

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>>.

我现在认为,如果一个完美"的引用包装器是可能的,那么引用可以只实现指针,我们就不需要T&但只是有一个库功能 reference 在所有方面都与 T& 完全一样......

I now think that if a "perfect" reference wrapper were possible, then references could be just implemented with pointers and we wouldn't need T& but just simply have a library feature reference<T> that works exactly like T& in all respects....

... 这反过来意味着该语言可以允许您在类型上重载" & 属性以生成自定义类型而不是语言引用.例如 使用 mytype&= custom_reference_emulator_of_mytype.

... which in turn means that the language could allow you to "overload" the & attribute over types to produce a custom type instead of a language reference. For example using mytype& = custom_reference_emulator_of_mytype.

推荐答案

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.)

相关文章