C ++ casting partial array (at some offset) for another type

The OpenCV library Vec4f

defines it as a floating point with four tuples, similar to this:

struct Vec4f {
    float data[4];

    /* here we may have some methods for this struct */
    inline float operator [] (int i) { return data[i]; }
};

      

It is sometimes used to represent a row: data [0-1] represents the unit directional vector of that row, and data [2-3] represents a point on that row.

In many cases I need to convert it to a two-point "Point". In OpenCV, a point (or vector) is defined as shown below:

struct Point2f {
     float x;  // value for x-coordination
     float y;  // value for y-coordination
};

      

I want to convert a string:

Vec4f myLine;

      

to the directional vector and a point on this line:

Point2f  & lineDirectionalVector;
Point2f  & linePoint;

      

I don't want to copy it, so I just use links. Thus, I wrote:

Point2f  & lineDirectionalVector =  *(Point2f*)(&myLine[0]);
Point2f  & linePoint=  *(Point2f*)(&myLine[2]);

      

The question arises: is this a good practice? If not, how do I go about it? Presumably, the first can be written as follows:

Point2f  & lineDirectionalVector = reinterpret_cast<Point2f>(myLine);

      

Any suggestions? Preferred Ways? Or maybe I'll just make a copy like this:

Point2f  lineDirectionalVector(myLine[0], myLine[1]);
Point2f  linePoint(myLine[2], myLine[3]);

      

which is more readable ...

+3


source to share


1 answer


The Eigen C ++ Linear Algebra Library does what you want a little more top-notch with vector segment, head and tail methods. It is usually best to accept what is trying to make it first class as there are various bugs in what you typed, which can take a while to track down, and if you ask which is the most readable it is good that the code will always raise some hair on the back of the neck ... also the OpenCV concept entirely against vec is questionable.



It's worth noting, however, that the arrays are guaranteed to be contiguous without indentation, so there is no problem with different with something like that. You need to be careful with casting structures such as Point2f, although alignment and padding issues can easily arise when structures are involved. It is recommended to use static_asserts when you write this type of code and read the relevant parts of the standard.

+2


source







All Articles