C++ 通过引用覆盖模板 class 和 return 的成员访问运算符

C++ override member access operator for template class and return by reference

是否可以通过引用覆盖模板 class 和 return 中的 -> 运算符?

我看到了这个post:Overloading member access operators ->, .*

还有一个通过引用覆盖 -> 和 return 的示例,但我无法将其用于模板。这是我正在努力实现的一个小例子:

#include <iostream>

using namespace std;

class A
{
public:
    void do_something()
    {
        cout << "Hey there";
    }
};

template<class T>
class Ref
{
public:
    Ref(T* ptr)
    {
        objPtr = ptr;
    }

    // this is another alternative, but I don't want to write Get() every time I want to access the object
    T& get() { return *objPtr; }

    template <class T>
    Ref<T>& operator->() const { return *objPtr; }

    // doesn't work either
    //T& operator->() const { return *objPtr; }

    // this works as expected, but I really MUST return by reference
    //T* operator->() const { return objPtr; } 

private:
    T* objPtr;
};

int main()
{
    A myObj;
    Ref<A> ref(&myObj);

    // error C2675: unary '->': 'Ref<A>' does not define this operator or a conversion to a type acceptable to the predefined operator
    ref->do_something(); 

    return 0;
}

如何做到这一点?

如果您 return 引用,则不能在需要指针的 ref->do_something(); 中使用它。您将不得不使用这种繁琐的方法:

ref.operator->().do_something(); 

而不是 return 指针 - 并使其成为 T*(或 const T*),而不是 Ref<T>*

示例:

#include <iostream>

class A {
public:
    void do_something() {
        std::cout << "Hey there\n";
    }
};

template<class T>
class Ref {
public:
    Ref(T& ptr) : objPtr(&ptr) {} // taking a T& but storing a pointer

    const T* operator->() const { return objPtr; }
    T* operator->() { return objPtr; }

private:
    T* objPtr;
};

int main() {
    A myObj;
    Ref<A> ref(myObj);

    ref->do_something(); 
}