以下代码是对象包装器的简化版本。我希望能够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!
}
Run Code Online (Sandbox Code Playgroud)
谁能建议一种方法来做到这一点?
我认为你需要重载运算符->和/或*(这就是智能指针的完成方式):
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();
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/ErEbxWE4P
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |