Boost logo

Boost Users :

From: Arkadiy Vertleyb (vertleyb_at_[hidden])
Date: 2005-09-07 18:35:48


"Steven Allmaras" <steven.r.allmaras_at_[hidden]> wrote

> I would like to do a compile-time mapping of an array accessor to a list
of
> scalars as in the following class:
>
> class MyArray1 {
> public:
> double& operator[](int n) { ??? }
>
> private:
> double a0, a1, a2, a3 ;
> } ;
>
> int main() {
> MyArray1 x ;
>
> x[1] = 2. ;
> }

How about something like this:

#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/enum_params.hpp>
#include <boost/mpl/int.hpp>
#include <iostream>

using namespace std;

#define DEFINE_FUNC(z, n, _)\
    double& operator[](boost::mpl::int_<n>)\
    {\
        return a ## n;\
    }

#define DEFINE_ARRAY(Name, n)\
    class Name\
    {\
    public:\
        BOOST_PP_REPEAT(n, DEFINE_FUNC, ~)\
    private:\
        double BOOST_PP_ENUM_PARAMS(4, a);\
    };

DEFINE_ARRAY(MyArray1, 4)

int main()
{
  MyArray1 x;

  x[boost::mpl::int_<0>()] = 2.;
  x[boost::mpl::int_<3>()] = 5.;
  // x[boost::mpl::int_<4>()] = 7.; // compile error

  cout << x[boost::mpl::int_<0>()] << endl;
  cout << x[boost::mpl::int_<3>()] << endl;
}

Regards,
Arkadiy


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