Boost logo

Boost :

Subject: [boost] An extension to boost::variant
From: Chris Hamilton (chamilton_at_[hidden])
Date: 2009-02-06 16:54:40

While boost::variant is very capable at what it does, there is one thing
it doesn't do (and maybe with very good reason, which I'm sure somebody
on this list will be capable of pointing out to me if this is the case ;)

Anyhow, boost::variant requires each of the enclosed types to be
assignable, which is clearly not met of a reference type. My question
is this: why can't boost::variant be clever about reference data types
(detected using type_traits is_reference), and internally store them as
pointers (type derived by using type_traits remove_reference). The
outside API (assignment, output streaming, visitation, comparison, etc)
could still treat the object as a reference.

The reason I want this, is to have a nice String variant, that
encapsulates the various forms a string can take in a current project:
std::strings, char*'s, and std::string* and
boost::shared_ptr<std::string>. I want functions to be able to handle
all of these types transparently by using variants as the argument
types. Allowing "const std::string&" as a variant type allows this to
be done while not requiring a wasteful string copy.

Are there any caveats to this that I should be aware of?

(I have a small custom variant class implementing this, and it appears
to work well. It's not as 'full fledged' as the boost::variant class,
but the approach I've taken could surely be grafted on to boost::variant.)


Chris Hamilton

Boost list run by bdawes at, gregod at, cpdaniel at, john at