使用operator()()无括号?

发布于 2025-02-02 09:40:11 字数 691 浏览 3 评论 0原文

以下代码是对象周围包装器的愚蠢版本。我希望能够无缝访问基础对象,也就是说,无需括号,如评论所描述的那样:

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

有人可以建议这样做吗?

The following code is a dumbed down version of a wrapper around an object. I would like to be able to access the underlying Object seamlessly, that is, without the need for parentheses, as the comments describe:

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

Can anyone please suggest a way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悟红尘 2025-02-09 09:40:11

我认为您需要超载操作员- &gt;和/或*(这是完成智能指针的方式):

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

I think you need overload operator -> and/or * (this is how smart pointers are done):

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文