How to write a C ++ conversion operator that returns a reference to an array?

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?

+7
c ++ arrays operator-overloading implicit-conversion
source share
2 answers

In fact you can, you almost had it with the latter:

 (&operator float())[3]; 

Regarding the question of whether typedef is ever really needed, I think this is from reading comments on https://stackoverflow.com/a/165359/ ... (which answer helped me also get the syntax of the above).

Edit

Apparently, this syntax is incorrect, and returning an array reference is forbidden as the chris we discovered. I think you just need to settle for typedef .

+3
source share

If you are using C ++ 11, the problem can be solved by entering the aliases of the ref / ptr template, as defined below:

 template<typename T> using ref = T&; template<typename T> using ptr = T*; 

Using these aliases, the declaration of the reference to the array conversion operator will take the form:

 operator ref<float[3]>(); 

It also makes the function of accepting / returning a pointer to a function / array declaration cleaner, for example:

 ptr<int()> foo(ptr<int(int)> bar); 

Instead:

 int (*foo(int(*bar)(int)))(); 
+5
source share

All Articles