Trying to create a reference wrapper similar to std::reference_wrapper, but with possibility to call the methods of the wrapped object.
#include <iostream>
class A {
public:
void f() {
std::cout << "A::f()\n";
}
};
class WrapA {
public:
WrapA(A& a) : _a_ptr{&a} {}
operator A&() {
return *_a_ptr;
}
private:
A* _a_ptr;
};
int main() {
A a;
WrapA wrap{a};
wrap.f(); // Fails with compile error: ‘class WrapA’ has no member named ‘f’
static_cast<A>(wrap).f(); // Works
return 0;
}
Why calling class A function f() on the wrapper object doesn't work, although implicit conversion from WrapA to A is possible? Is there some way to work around this issue?
Tried using std::reference_wrapper and it fails with same compile error.
One way to get this type of behavior is to overload the arrow operator
operator ->and have it return a pointer to the wrapped object. That will get applied recursively by the compiler on the returned pointer and let you call the member function. That would give youwhich outputs
and you can see it working in this live example.