Boost logo

Boost Users :

From: Philippe Mori (philippe_mori_at_[hidden])
Date: 2005-09-07 08:07:57


>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 ;
> } ;
>

Well, using an union would typically works correctly. And if you are using a
compiler with some kind of property, this might be another solution.
FInally, you could have functions that access the array. A final solution,
would be to derive from a struct and do a reinterpret_cast.

---

The first solution might look like :

union {
    struct { double a0, a1, a2, a3 ; } scalar;
    double array[4];
};

but then you would need to qualify names.

---
For the second solution, you will be able to have the desired syntax for the 
caller... but properties are not standard C++ and are not protable.
---
For the third solution, it will be something like :
class MyArray1 {
public:
    double &a1() { return array[1]; }
    double const &a1() const { return array[1]; }
private:
    double array[4];
};
---
The forth solution is something like :
struct MyArray1Struct {
    double a0, a1, a2, a3;
};
class MyArray1 : private MyArray1Struct
{
public:
    double& operator[](int n) { return 
reinterpret_cast<double(&)[4]>(static_cast<>(*this)); }
    double const & operator[](int n) const { return reinterpret_cast<double 
const(&)[4]>(static_cast<>(*this)); }
};

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