简体   繁体   English

如何使用 C++ 模板模拟类型的引用?

[英]How to simulate reference of a type with C++ templates?

I want to wrap a reference of a type with a class to add other functionality to it, something like below, but I don't want to force the use of a function or operator to access base type methods.我想用 class 包装一个类型的引用,以向它添加其他功能,如下所示,但我不想强制使用 function 或运算符来访问基本类型方法。

class A {
    private:
        int fX;
    public:
        void SetSomething(int x){ fX = x; }
        int GetSomething() { return fX; }
};

template<typename T>
class Ref {
    private:
        T& fRef;
    public:
        Ref(T &ref) : fRef(ref) {}
        inline operator T&() { return fRef; }
};

int main() {
    A a;
    Ref<A> ref(a);
    ref.SetSomething(100);
    return 0;
};

https://godbolt.org/z/8x8aehb8e https://godbolt.org/z/8x8aehb8e

Is possible to implement this kind of template?有可能实现这种模板吗?

Unfortunately, transparent proxies are not currently possible in C++.不幸的是,透明代理目前在 C++ 中是不可能的。 You can either inherit from the type, implement operator-> or recreate the whole interface.您可以从类型继承,实现operator->或重新创建整个接口。 I usually rewrite the whole interface in the reference type.我通常在引用类型中重写整个接口。

You could use std::reference_wrapper你可以使用std::reference_wrapper

std::reference_wrapper on cppreference cppreference 上的 std::reference_wrapper

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. std::reference_wrapper 是一个 class 模板,它将引用包装在可复制、可分配的 object 中。 It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.它经常被用作将引用存储在通常不能保存引用的标准容器(如 std::vector)中的一种机制。

Their example:他们的例子:

    std::list<int> l(10);
    std::iota(l.begin(), l.end(), -4);
    std::vector<std::reference_wrapper<int>> v(l.begin(), l.end());
    // Then you can simulate random access on a list :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM