Is there a better or more efficient way to cast a cv::Vec<double, 4> to cv::Vec<double, 3>.
The example shows my current solution using reinterpret_cast. Where I like to point out that the vector c points to the same data as vector a but as a cv::Vec<double,3>.
cv::Vec<double, 4> a(1,2,3,4);
cv::Vec<double, 3> b(5,6,7);
std::cout << "a: " << a << ", b: " << b << std::endl;
cv::Vec<double, 3> &c = reinterpret_cast<cv::Vec<double, 3>&>(a);
c = b;
std::cout << "a: " << a << ", b: " << b << std::endl;
output:
a: [1, 2, 3, 4], b: [5, 6, 7]
a: [5, 6, 7, 4], b: [5, 6, 7]
In order to make my point clear
In my use case, I have to operate on a huge set of cv::Vec4d object instances. And I would like to avoid copping data to back and forth.
Using
cwould be undefined behavior.cis an lvlaue of a typeVec<double, 3>which refers to an object of typeVec<double, 4>. Using it is UB as per [basic.lval] p11. See also What is the Strict Aliasing Rule and Why do we care?It doesn't matter that these two types are "vaguely similar", and that they both store a
double[]of some size, although that similarity makes it "work" on your machine.The proper way would be to create a new
cv::Vec<double, 3>:This uses the constructor of
cv::Vecwhich takes aconst double*.