Boost logo

Boost Users :

Subject: Re: [Boost-users] variant: bounded types derive from same base class
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2009-08-03 08:59:20


Hi!

With variant you don't need the base class at all. Usually you know in the
context of your app, which object should be there.

In that case you implement the generic visitor:

struct my_visitor
{
   typedef result_type void;

   template<class T>
   result_type operator()(T const& all_other)
   {
      // this is usually an error, because this type is unexpected in the
current context
   }

   result_type operator()(ABCDerived1 const& derived1)
   {
      // handle derived1 here
   }

   result_type operator()(ABCDerived2 const& derived2)
   {
      // handle derived2 here
   }

   ...

   result_type operator()(ABCDerivedN const& derivedN)
   {
      // handle derived2 here
   }
};

You can also work with template specialization and define specialized
operator() in place where the ABCDerivedN is known.

Hope that helps,
Ovanes

On Mon, Aug 3, 2009 at 2:35 PM, Hicham Mouline <hicham_at_[hidden]> wrote:

> Hello,
>
> I have a library with an abstract base class ABC and derived classes D1...
> Dn.
> These classes cannot be changed.
>
> User code wants to write code that depends on which concrete type the
> object
> being passed.
>
> User writes:
>
>
> void f( const ABC& abc )
> {
> Tag t = abc.GetTag() ; // Tag is an enum for all the derived types,
> delivered by the lib
> Switch (t)
> { case:
> case:
> case:
> }
> }
> /// SO ugly, nevertheless if some case is missing, g++ for e.g. prints
> warnings
>
>
> I am told this is the visitor pattern
>
> I then looked at boost::variant<>
>
> The lib could deliver
>
> typedef boost::variant<D1, ... , Dn> ABCDerived;
>
> and the user could write visitors to visit ABCDerived objects,
> here the user is enforced to implement all cases in the visitor.
>
> but then the function f expects ABC objects. Can I still do:
>
> void f( const ABC& abc )
> {
> // how to write code to use the visitors with abc ?
> }
>
> Rds,
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>



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