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

Viewed 84

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 ?

1 Answers

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.

Related