In C ++, you can add implicit conversion operators to a class or structure. For example, three-dimensional vector types typically include something like:
struct Vector { float x, y, z; operator float * () { return reinterpret_cast<float *>(this); } };
to allow access to vector elements with indices, passing to functions that want a pointer, etc. It occurred to me to ask a question: is it possible to write a conversion operator instead that returns a reference to the float array instead of a pointer to float?
(This is a purely academic interest. I do not know what advantages a reference to an array has, if any, by a simple pointer.)
As a free function, we can do this as follows:
float (&convert(Vector & v))[3] { return reinterpret_cast<float(&)[3]>(v); } Vector v; convert(v);
However, I could not find the correct syntax for this as a conversion operator. I 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 that returns a reference to an array, and if so, what is the syntax for this?
c ++ arrays operator-overloading implicit-conversion
Nathan reed
source share