Boost logo

Boost :

From: Vesa Karvonen (vesa.karvonen_at_[hidden])
Date: 2001-08-29 15:06:28

From: "Douglas Gregor" <gregod_at_[hidden]>
[... on optional ...]
> I was recently working on a variant type that was intended to be created on
> the stack. I believe it is possible to do, though it isn't trivial :).

If I understand intention behind 'variant' correctly (I think of 'variant' as
a safe union that allows types with constructors and destructors) then I agree
that it should be doable, but it is somewhat tricky to get it right:
- alignment
- exception safety
- safe/unsafe vswitch

Now, if understand 'variant' correctly, then it seems to me that 'optional'
could be implemented something like this (without run-time overhead on an
ideal, but not "magical", compiler):

    template<class t>
    struct optional
      variant<t,void> v;

'optional' could also be implemented using 'any', but this would imply
considerable run-time overhead.

I think that 'variant', 'optional', 'any' and smart pointers all have
similarities but also significant intentional differences.

NOTE: The following reflects my current thinking - it is more than likely that
I have misunderstood some of the concepts.

[I would rather arrange these into a nice table, but text based e-mail just
doesn't cut it.]

- optional: signaling errors/uncomputable results, lazy initialization
- variant: safe union ???
- any: typeless programming (it seems like a "boxed value")
- smart pointer: avoiding resource leaks/automatic finalization, exception

- optional: lazy
- variant: ???
- any: lazy
- smart pointer: strict (or this is how I see the matter)

Should 'variant' support lazy initialization? Parhaps variant<> should support
being left unitialized only if 'void' is one of the variant types.

What about 'any'? Should it be 'any_or_none' or 'optional_any'?

- optional: monomorphic
- variant: bounded polymorphic ???
- any: unbounded polymorphic / typeless
- smart pointer: subtype polymorphic (typically)

Copy semantics:
- optional: value
- variant: value
- any: value
- smart pointer: reference, destructive copy or value (clone)

The smart pointer concept seems rather overloaded.

Syntax / operations:
- optional: pointer
- variant: vswitch, empty, cast, type ???
- any: empty, cast, type
- smart pointer: pointer

I think that all of the above concepts should be further refined. For
- 'any' could probably make use of the 'vswitch' syntax.
- 'variant<T,void>' seems very close to 'optional<T>'.
- 'variant' and 'any' might or might not make use of some pointer syntax.

Assuming that optional and variant make it into Boost, I think that Boost
should have documentation which describes the differences between these
concepts and should perhaps include a decision tree for choosing the best

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