In C++ one can add implicit-conversion operators in a class or struct. For instance, 3D vector types usually include something like:
struct Vector {
float x, y, z;
operator float * () { return reinterpret_cast<float *>(this); }
};
to allow accessing the vector's elements with subscripts, passing to functions that want a pointer, etc. It occurred to me to wonder: can we instead write a conversion operator that returns a reference to array of float, instead of a pointer to float?
(This is of purely academic interest. I don't know what benefits a reference-to-array would have, if any, over a simple pointer.)
As a free function we can do this like:
float (&convert(Vector & v))[3]
{
return reinterpret_cast<float(&)[3]>(v);
}
Vector v;
convert(v);
However, I haven't been able to find the right syntax to do this as a conversion operator. I've tried things like:
operator float(&)[3] ()
operator float(&())[3]
float (&operator())[3]
and various other permutations, but I just get various syntax errors (g++ 4.8.1).
Is it possible to write a conversion operator returning a reference to array, and if so, what is the syntax to do so?