使用operator()()无括号?
以下代码是对象周围包装器的愚蠢版本。我希望能够无缝访问基础对象
,也就是说,无需括号,如评论所描述的那样:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要超载操作员
- &gt;
和/或*
(这是完成智能指针的方式):https://godbolt.org/z/erebxwe4p
I think you need overload operator
->
and/or*
(this is how smart pointers are done):https://godbolt.org/z/ErEbxWE4P