1

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;

2 Answers 2

4
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;
Sign up to request clarification or add additional context in comments.

4 Comments

nice, but is there a way without using typedef ?
You can use identity like operator identity<int[size]>::type &() { return araye; }. 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: I thought identity would do, but was surprised to find that GCC 4.2 chokes on it. As do Comeau & GCC 4.5.
@Johannes: Ouch, how could i miss that. :D
-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.