Boost logo

Boost Users :

Subject: Re: [Boost-users] Help with (possibly MPL) pattern for a viewer that may contain a copy of statically allocated data
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-01-24 15:19:07


AMDG

Jesse Perla wrote:
> I am wondering what the best pattern/approach for a data structure
> that may contain either a reference or a copy of some data used in a
> constructor. I would love the opportunity to have the data structure
> capable of conditionally storing the data for the data copy on the
> stack. Are there any fancy generic tricks/patterns to do this using
> boost::mpl, etc.?
>
> So to put in some pseudocode notes for discussion to get the point
> across of what I think I want:
>
> boost::array< boost::array<double, M>, N> myaxis; //creates axis in a
> stack allocated data structure.
> regular_grid<M, N, COPYDATA> my_grid(axis_values);
> regular_grid<M, N, REFDATA> my_grid(axis_values);
>
> template<int M, int N, int ConstructionPolicy>
> class regular_grid
> {
> boost::array< boost::array<double, M>, N>& axis_ref_; //Reference
> to the axis, either static or actual reference. All code in the class
> would use this, not axis_
>
> STATIC_IF(ConstructionPolicy == COPYDATA)
> {
> boost::array< boost::array<double, M>, N> axis_;
> regular_grid(const boost::array< boost::array<double, M>,
> N>& axis) : axis_(axis), axis_ref_(axis_) //constructor makes copy,
> sets ref to copy.
> {
> }
>
> }
> STATIC_ELSE(ConstructionPolicy == REFDATA)
> {
> regular_grid(const boost::array< boost::array<double, M>,
> N>& axis) : axis_ref_(axis) {} //constructor just uses the ref.
> }
> };
>
> Is this possible? any ideas on code to look at to see how to do it?

If you don't need to decide at runtime whether to store a copy or a
reference, then
you can avoid the reference when you have a copy using static polymorphism:

template<int M, int N, class Storage = boost::mpl::identity<> >
class regular_grid {
    typedef boost::array< boost::array<double, M>, N > array_type;
    typedef typename boost::mpl::apply<Storage, array_type>::type
storage_type;
    storage_type axis_;
    // use axis
};

typedef boost::add_reference<boost::add_const<boost::mpl::_1> >
reference_policy;
typedef boost::mpl::identity<> copy_policy;

regular_grid<2, 3, reference_policy> g;

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net