I'm having trouble understanding the proper way to cast to array reference types and I would appreciate any help you can provide!
The code I'm working on requires may small computations using coordinate pairs. I've chosen to use array references to represent (x,y) coordinate pair since they are lightweight and provide better bounds checking than do pointers. For example, here's the function header for one function that calculates the cross product of two vectors, ij and ik:
The legacy software I'm working with generates the necessary coordinates as the result of a query, but returns them in a large 1D array:
double * data = do_query();
I know that xy coordinate pairs are always adjacent in this array, so what I want to do is create a reference to a two-element array that is an alias for two adjacent elements in a larger array. I wish I could say something like the following:
// Doesn't compile.
const double (&i)[2] = data[i_pos];
const double (&j)[2] = data[j_pos];
const double (&k)[2] = data[k_pos];
double answer = cross_product(i,j,k);
I don't see anything in the C++ standard that addresses array references specifically, and nothing short of reinterpret_cast will allow this conversion to succeed. Does anyone know whether there is a standard-compliant way of doing this?
Question
WOMBAT_
Hi,
I'm having trouble understanding the proper way to cast to array reference types and I would appreciate any help you can provide!
The code I'm working on requires may small computations using coordinate pairs. I've chosen to use array references to represent (x,y) coordinate pair since they are lightweight and provide better bounds checking than do pointers. For example, here's the function header for one function that calculates the cross product of two vectors, ij and ik:
inline double cross_product(const double (&i)[2], const double (&j)[2], const double (&k)[2] )
The legacy software I'm working with generates the necessary coordinates as the result of a query, but returns them in a large 1D array:
double * data = do_query();
I know that xy coordinate pairs are always adjacent in this array, so what I want to do is create a reference to a two-element array that is an alias for two adjacent elements in a larger array. I wish I could say something like the following:
// Doesn't compile.
const double (&i)[2] = data[i_pos];
const double (&j)[2] = data[j_pos];
const double (&k)[2] = data[k_pos];
double answer = cross_product(i,j,k);
I don't see anything in the C++ standard that addresses array references specifically, and nothing short of reinterpret_cast will allow this conversion to succeed. Does anyone know whether there is a standard-compliant way of doing this?
Thanks!
Link to comment
Share on other sites
3 answers to this question
Recommended Posts