Boost logo

Boost :

From: Rainer Deyke (root_at_[hidden])
Date: 2001-03-25 21:27:28

----- Original Message -----
From: "David Abrahams" <abrahams_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Sunday, March 25, 2001 4:28 PM
Subject: Re: [boost] Python: is there any way to make this work?

> Hi Rainer,
> I don't think I can help you make it work "as expected", since I'm not
> certain what you expect. I can see many problems with the code you posted
> that would prevent it from working.
> 1. you need to use boost::shared_ptr or some other smart pointer that
> actually exists (e.g. std::auto_ptr)

That's what I meant.

> 2. you can't rely on implicit conversion from B in make_A() since both of
> the smart pointers I mentioned have explicit constructors

The following compiles fine on my system, Visual C++ 6.0 SP4:

boost::shared_ptr<int> f() { return new int(5); }

Maybe it shouldn't, but it does.

> 3. class A needs a virtual destructor, since you will be destroying a B
> through the A pointer.

I know. I had that in my original code, but forgot it when writing a simple
stripped-down example.

> 4. class A needs to declare f as a (possibly pure) virtual function. This
> isn't Python; in C++, run-time polymorphism requires a declaration of
> polymorphic functions in base classes!

I am working with events here. If I was working in pure C++, I might do
something like this:

void handle_event(const Event& e)
  KeyboardEvent *ke = dynamic_cast<KeyboardEvent *>(&e);
  if (ke) {
    // handle keyboard event
  MouseEvent *me = dynamic_cast<MouseEvent *>(&e);
  if (me) {
    // handle mouse event

In Python there is no concept of static type, so I expected the
'dymanic_cast's to become unnecessary. I could get the functionality I want
right now by writing a conversion function:

boost::python::ref convert_event(boost::shared_ptr<Event> e)
  KeyEvent *ke = dynamic_cast<KeyEvent *>(e.get());
  if (ke) {
    // There is no way to downcast a shared_ptr, so return copy of event
    return boost::python::to_python(*ke);
  MouseEvent *me = dynamic_cast<MouseEvent *>(e.get());
  if (me) {
    return boost::python::to_python(*me);

What I expected was for 'boost::python::to_python' to automatically perform
this conversion, minus the unsafe copy-instead-of-reference hack. (There
really should be a way to downcast smart pointers.) The Boost Python
Library already knows about my class hierarchy and is already willing to
downcast, so why does it not perform this conversion?

Rainer Deyke (root_at_[hidden])
Shareware computer games           - 
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

Boost list run by bdawes at, gregod at, cpdaniel at, john at