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

Moh*_*nTi 2 c++ reflection templates

我想用类包装类型的引用以向其添加其他功能,如下所示,但我不想强制使用函数或运算符来访问基类型方法。

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;
};
Run Code Online (Sandbox Code Playgroud)

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

可以实现这种模板吗?

Gui*_*cot 6

不幸的是,透明代理目前在 C++ 中是不可能的。您可以继承该类型、实现operator->或重新创建整个接口。我通常用引用类型重写整个接口。