Boost logo

Boost :

From: Joel de Guzman (djowel_at_[hidden])
Date: 2003-10-04 05:12:51


Sounds like a variant to me. What am I missing?

-- 
Joel de Guzman
http://www.boost-consulting.com
http://spirit.sf.net
E. Gladyshev <egladysh_at_[hidden]> wrote:
> Just wondering does boost have something similar to C unions
> so that you could create heterogenious containers?
> 
> Something like the following working pseudo-code
> 
> template < typename Types >
> struct union2
> {
>     typedef typename boost::mpl::at_c<Types, 0 >::type type1;
>     typedef typename boost::mpl::at_c<Types, 1 >::type type2;
> 
>     union2() : obj_(0)
>     {
>     }
>     union2( const union2<Types>& l ) : obj_(0)
>     {
>         create( l.t_ );
>         copy( l.obj_ );
>     }
>     virtual ~union2()
>     {
>         free();
>     }
> 
>     void create( size_t t )
>     {
>         free();
>         t_ = t;
>         switch( t_ )
>         {
>         case 0:
>             obj_ = new type1;
>             break;
> 
>         case 1:
>             obj_ = new type2;
>             break;
> 
>         default:
>             throw;
>         }
>     }
> 
> private:
>     size_t t_;
>     void *obj_;
>     void free()
>     {
>         if( !obj_ ) return;
>         switch( t_ )
>         {
>         case 0:
>             delete static_cast<type1*>(obj_);
>             break;
> 
>         case 1:
>             delete static_cast<type2*>(obj_);
>             break;
> 
>         default:
>             throw;
>         }
>         obj_ = 0;
>     }
> 
>     void copy( void* obj )
>     {
>         switch( t_ )
>         {
>         case 0:
>             *static_cast<type1*>(obj_) = *static_cast<type1*>(obj);
>             break;
> 
>         case 1:
>             *static_cast<type2*>(obj_) = *static_cast<type2*>(obj);
>             break;
> 
>         default:
>             throw;
>         }
>     }
> };
> 
> main()
> {
>   typedef notus::union2< boost::mpl::vector2<char, short> > my_union;
> 
>   std::vector< my_union > gv;
> 
>   my_union u(0);
>   my_union u1(1);
>   gv.push_back( u );
>   gv.push_back( u1 );
> }
> 
> 
> Eugene
> 
> 
> __________________________________
> Do you Yahoo!?
> The New Yahoo! Shopping - with improved product search
> http://shopping.yahoo.com
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk