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
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
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@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users