Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-06-12 08:02:32


On Wednesday 12 June 2002 06:02 am, Yitzhak Sapir wrote:
> > -----Original Message-----
> > From: Douglas Gregor [mailto:gregod_at_[hidden]]
> >
> > When does one prefer the boost::any storage method instead of
> > the on-stack
> > method? The on-stack approach is a lightweight approach that closely
> > resembles C-style unions; in the cases where variant objects
> > are too large to
> > put on the stack, the variant objects can easily be allocated
> > on the heap
> > (just like we would do with a C-style union). The only cases
> > where on-stack
> > allocation isn't feasible occur with recursive or incomplete
> > types (discussed
> > later...). So, I would say that we should only use on-stack
> > allocation but
> > allow an 'escape' to heap allocation for recursion and
> > incomplete types.
>
> boost::any also allows an infinite range of types that may not necessarily
> be incomplete. For example, you could have a union of all types that
> inherit from some common base type (Shape), or a union of any instantiation
> of a templated type

I would think that these would be different variants on the discriminated
union theme (pun intended). boost::any is a nearly unbounded variant (it
requires copy-construction) and there are any number of ways that we can
bound the set of types for a new variant type. I've found the need for a
variant whose set is bounded to a known, finite set of types at compile time.

I'm not quite sure how this relates to my question: if we assume that variant
is given a finite, known set of types that it can hold at compile time, why
would we use heap allocation as in boost::any?

> (I wonder if it is possible to check the existence of a
> class as part of a templated type at compile time -- perhaps using the "has
> member" compile time test).

Sure. You're looking for a variant that will only store types that are
instantiations of a given class template. The signature might look like this:

  template<template<class T> class Template>
  class instantiation_variant {
    // ...
  };

You can check if something is an instantiation of Template this way:

  template<template<class T> class Template, typename I>
  struct is_instantiation {
    BOOST_STATIC_CONSTANT(bool, value = false);
  };

  template<template<class T> class Template, typename T1>
  struct is_instantiation<Template, Template<T1> > {
    BOOST_STATIC_CONSTANT(bool, value = true);
  };

        Doug


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