Automatically converting an A* into a B*

Posted by Xavier Nodet on Stack Overflow See other posts from Stack Overflow or by Xavier Nodet
Published on 2010-04-26T17:08:18Z Indexed on 2010/04/26 17:23 UTC
Read the original article Hit count: 191

Hi,

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);
  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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about user-defined-convertions