使用不带括号的 operator()()?

Use of operator()() without parentheses?

以下代码是对象包装器的简化版本。我希望能够无缝地访问底层 Object,也就是说,不需要括号,如评论所述:

struct A
{
  void Func() {}
};

template <typename Object>
struct ObjectWrapper
{
  ObjectWrapper(Object& o) : object_(&o) {}

  operator Object& () { return *object_; }
  Object& operator ()() { return *object_; }

  Object* object_;
};


int main()
{
  A a;
  ObjectWrapper<A> obj(a);

  //
  // Trying to call Func() on the A object that 'obj' wraps...
  //

  obj.operator A& ().Func(); // Messy

  obj().Func(); // Better but still has parentheses

  // I really want to be able to say this:
  // obj.Func()
  // ...but cannot see how!
}

任何人都可以建议这样做的方法吗?

尝试继承 Object。请参阅 ObjectWrapper 中的 void Func() 只是多余的,仅当您需要一些拦截逻辑时:

struct A {  void Func() {} };

template <typename Object> struct ObjectWrapper: public Object
{
  ObjectWrapper(Object& o) : Object(o) {}
  void Func() {cout<< "intercept Object::Func"; Object::Func();}

};
int main()
{
  A a;
  ObjectWrapper<A> obj(a);
  obj.Func();
}

另请参阅您的代码,在 object_(&o)

中使用 &
   ObjectWrapper(Object& o) : object_(&o) {}

我认为你需要重载运算符-> and/or *(智能指针就是这样实现的):

template <typename Object>
struct ObjectWrapper {
    ObjectWrapper(Object& o)
        : object_(&o)
    {
        LOG();
    }

    Object* operator->() const
    {
        LOG();
        return object_;
    }

    Object& operator*() const
    {
        LOG();
        return *object_;
    }

    Object* object_;
};

int main()
{
    A a;
    ObjectWrapper<A> obj { a };
    obj->Func();
    (*obj).Func();
}

https://godbolt.org/z/ErEbxWE4P