Reputation: 313
I am currently writing a wrapper over an existing class. What is the best way to write a wrapper without changing any client code that used the existing class directly?
class A
{
public:
void foo() {}
};
template<typename T>
class Wrapper
{
// ...other wrapper data/functionality...
private:
T myObject;
};
main()
{
Wrapper<A> wrappedA;
wrappedA.foo();
}
Compilation fails in msvc with error C2039: 'foo' : is not a member of 'Wrapper'
What is the best way to make the template wrapper class work without changing any code in main?
Edit
Upvotes: 1
Views: 96
Reputation: 327
Provide operator-> returning pointer to the wrapped class if having to use -> to access methods is not an issue:
template
class Wrapper
{
public:
T* operator->() { return &myObject; }
T const* operator->() const { return &myObject; }
...
};
But if you really want dot to be used to access methods, then maybe derive Wrapper from T? (but then your class is not much of a Wrapper at all :D)
Upvotes: 2
Reputation: 227370
You need to call it via the A
instance:
wrappedA.myObject.foo();
Your wrapper isn't a very clever wrapper, so you need to know that it holds an instance called myObject
. You can make it clever by giving it a conversion operator:
template<typename T>
class Wrapper
{
public:
T myObject;
operator const T& () const { return myObject; }
operator T& () { return myObject; }
};
This will allow you to use it in places where an A
is required:
void bar(const A& a) { a.foo(); } // (make A::foo() a const method)
Wrapper<A> a;
bar(a); // OK
Upvotes: 3