Home > Software engineering >  How to simulate reference of a type with C templates?
How to simulate reference of a type with C templates?

Time:09-02

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

Is possible to implement this kind of template ?

CodePudding user response:

Unfortunately, transparent proxies are not currently possible in C . You can either inherit from the type, implement operator-> or recreate the whole interface. I usually rewrite the whole interface in the reference type.

CodePudding user response:

You could use std::reference_wrapper

std::reference_wrapper on cppreference

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

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 :)
  • Related