views:

325

answers:

3

two clients communicate to each other on top of a message layer

in the message body, I need include a field pointing to any data type

From client A, I send the field as a shared_ptr<TYPEA> to the message layer. I define this field as a shared_ptr<void> in the message layer. But how can I convert this field back to shared_ptr<TYPEA> in client B?

Or should I define shared_ptr<void> in message layer as something else?

Thanks

A: 

If all possible data types that you plan on passing between clients inherit from some common base class, you can simply include a flag variable in the base class which indicates which derived type the current instance is. Pass base-class pointers between clients, and then use dynamic_cast to downcast the base pointer to the appropriate derived type.

Charles Salvia
+1  A: 

If you're using boost::shared_ptr then you can use the various XXX_ptr_cast<>() functions (static_ptr_cast, dynamic_ptr_cast...).

If you're using the MSVC 2010 version I haven't been able to find an implementation of these functions. They may not be part of the standard.

Noah Roberts
The MSVC2010 version is dynamic_pointer_cast: http://msdn.microsoft.com/en-us/library/bb982967.aspx
bsruth
cast shared_ptr< void > var with std::tr1::static_pointer_cast< TYPEA >(var) does work. My mistake.cast TYPEA to void then static_cast to TYPEA equivelent to reinterpret_cast
+2  A: 

If the shared_ptrs & pointed-to data aren't held in memory common to both clients (e.g. the clients run in different processes, and the data isn't in shared memory), the pointers from one client won't be valid for the other. You'll need to construct a representation of the pointed-to data and transmit that. The receiver constructs its own copy of the data in the messaging layer and passes a shared_ptr to that up to the client.

outis