Boost logo

Boost Users :

From: Gianni Luciani (gianni.luciani_at_[hidden])
Date: 2001-11-10 00:52:51


On Fri, 9 Nov 2001 scleary_at_[hidden] wrote:

[ SNIP ]

> You could take a "nasty-hack" approach, if you *really* wanted to:
> 1) Add an 'any_base' class with a virtual function
> 2) Extend 'any' to return an 'any_base *' referring to the held value,
> using C-cast notation (derived-to-base when possible, reinterpret when not)
> 3) Derive your held value types from a common base class 'my_base', which
> was derived from 'any_base'; add the operations you want to perform to
> 'my_base'
> 4) Call the 'any' function returning 'any_base *', downcasting it to
> 'my_base'. This will result in undefined behaviour if the contained value
> is not actually derived from 'my_base' (because of the reinterpret_cast
> behaviour in step 2)
>
> I *think* that will work (never tried it). Messy, though, and IMO not
> generic enough to mess with.

I will try it, but it seems to me that this approach doesn't solve the
problem 'cause from any_base I cannot know the type of the contained
value; this type, infact is derived from any_base ... :-(

> Alternatively, you could:
> 1) Visit 'any'/'any::placeholder'/'any::holder' to provide:
> void any::action(any which) { content->action(which); }
> virtual void any::holder::action(any which) { any_action(held, which);
> }
> 2) Declare a function 'any_action(T, any)', where the any parameter
> designates which "operation" to perform. Overloading is then possible on T.
> Also, where T is a user-defined type, Koenig lookup can be used (abused?) to
> create different (non-overlapping) sets of "operations".

I don't understand this completely, but I think the core point is the set
of overloaded functions ... so I should add an overloaded fun for every
type I need ... seems a big loss of genericity to me :-(

> Just some thoughts. Again, I've never tried it.
However they are interesting: many thanks for Your ideas

I also try to restate my needs: I would like to be able to simulate the
following code fragment that uses virtual template funcs (but I started
thinking it's impossible):

class any{
...
template <typename newtype> void * cast_to()
{ if(ptr) ptr->cast_to<newtype>(); }
...
 class placeholder{
   ...
   virtual template <newtype> void * cast_to() = 0;
 };
 template <typename value_type>
 class holder : public placeholder{
  ...
   virtual template <newtype> void * cast_to(){
     // * here I know both value_type AND newtype *
     return dynamic_cast<newtype *>( &held );
   }
  const value_type held;
 };

placeholder * ptr;
};

Regards
Gianni Luciani


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net