Search code examples
c++proxysmart-pointersconversion-operator

Automatically converting an A* into a B*


Suppose I'm given a class A. I would like to wrap pointers to it into a small class B, some kind of smart pointer, with the constraint that a B* is automatically converted to an A* so that I don't need to rewrite the code that already uses A*.

I would therefore want to modify B so that the following compiles...

struct A {
  void foo() {}
};

template <class K>
struct B {
  B(K* k) : _k(k) {}
  //operator K*() {return _k;}
  //K* operator->() {return _k;}
private:
  K* _k;
};

void doSomething(A*) {}

void test() {
  A a;
  A* pointer_to_a (&a);
  B<A> b (pointer_to_a);
  //b->foo();             // I don't need those two...
  //doSomething(b);

  B<A>* pointer_to_b (&b);

  // Following represents existing code I don't want to change...
  pointer_to_b->foo();       // 'foo' : is not a member of 'B<K>'
  doSomething(pointer_to_b); // 'doSomething' : cannot convert parameter 1 from 'B<K> *' to 'A *'
}

Note that B inheriting from A is not an option (instances of A are created in factories out of my control)...

Is it possible?

Thanks.


Solution

  • The type of pointer_to_b is pointer to B, which is a type you cannot modify; it's implemented by the compiler.

    You can do (*pointer_to_b)->foo(), which will do the right thing (assuming you have the overridden operator->()). However, that won't let the other code do the right thing, if you pass pointer_to_be into it.

    Also let me add that you can override operator& on B to return an A*, which might solve your problem, depending on the specific use cases.