views:

71

answers:

2

I have following class:

template <size_t size>
class Araye{
 public:
  Araye(int input[]){
   for (int i=0;i<size;i++)
    araye[i]=input[i];
  }
  int araye[size];
};

How should I write a cast-to-reference-to-array operator for this class so that following works:

int adad[3]={1,2,3};
Araye<3> araye(adad);
int (&reference)[3]=araye;
+3  A: 
template <size_t size> class Araye {
public:
    typedef int (&array_ref)[size];    
    operator array_ref () { return araye; }
    // ...

Or with identity (thanks Johannes):

operator typename identity<int[size]>::type &() { return araye; }

With that your example works, but i'd prefer the following declaration instead:

Araye<3>::array_ref reference = araye;  

There usually should be no need for this though as the subscripting operator should cover most needs:

int& operator[](size_t i) { return araye[i]; }

Note that if you are ok with limiting your class to being an aggregate, you could shorten your sample to the following instead:

template <size_t size> struct Araye {
    int araye[size];
    typedef int (&array_ref)[size];    
    operator array_ref () { return araye; }
};

Araye<3> araye = {1,2,3};
Araye<3>::array_ref reference = araye;
Georg Fritzsche
@Georg Fritzsche: nice, but is there a way without using typedef ?
Pooria
You can use `identity` like `operator identity<int[size]>::type }`. There is no way in C++03 to have a conversion function template that converts to a reference to array, though. In this case, the size and base type is fixed, so we are fine.
Johannes Schaub - litb
Georg Fritzsche
@Georg ah right we need to write `typename` before it :)
Johannes Schaub - litb
@Johannes: Ouch, how could i miss that. :D
Georg Fritzsche
A: 

You could use the boost::array functionality, also found in TR1 and by extension C++0x.

DeadMG