Boost logo

Boost :

Subject: Re: [boost] [Interest] Value Dispatch
From: greened_at_[hidden]
Date: 2012-08-15 21:34:12


[Note: I don't know why my e-mail address got mangled. It should be
 "greened_at_..."]

Larry Evans <cppljevans_at_[hidden]> writes:

> Could you not use boost::variant

Thanks for your feedback!

boost::variant can do some similar things but I think it is really aimed
at a different problem. As I understand it, boost::variant's primary
use case is to function as a type safe generalized union. Thus it has
to deal with things like alignment, etc. that the presented technique
(which I call "value dispatch" for lack of a better name) does not. A
quick glance at boost::variant source code shows that it is quite
complex. IMHO, value dispatch is much simpler.

I was aiming for a value-centered analogue to virtual functions as
opposed to an enhanced union type. boost::variant feels opaque to me
(get<>, etc.) while value dispatch seems more natural and transparent
for the use cases I had in mind.

Note also that boost::variant appears to require or at least encourage
inheritance (e.g. static_visitor) while value dispatch does not. I
don't think that's a strong positive or negative as long as value
semantics are maintained.

That said, I'll now explain how I think inheritance might be useful with
value dispatch. :)

I think it should be possible to inherit from vehicle and/or
visitor<vehicle ...> to allow new behaviors for derived types while
maintaining value semantics. The trick is to figure out how to re-use,
for example, the vehicle::drive_impl and vehicle::visit_dispatch
routines without slicing. Making the object type a type parameter might
help. It is an interesting problem but I haven't really looked at it
yet.

A not-currently-existing C++ feature would also be helpful in avoiding
code duplication:

enum class my_kind : vehicle::kind {
  // Inherit vehicle::kind names and values
  Submarine,
  Tractor
};

Maybe all this isn't compelling over boost::variant but I've found it
quite useful in a large project.

                           -Dave


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