I want to extract the real part of a std::complex<double>
as a double
.
std::complex<double> c = 1.0;
double *d = reinterpret_cast<double*>(c); // Want this to be = 1.0
The following gives an error invalid cast from type 'std::complex<double>' to type 'double*'
. Is there an example on how to do this?
CodePudding user response:
double d = c.real();
Best read the documentation of std::complex before continuing to use it:
https://en.cppreference.com/w/cpp/numeric/complex
CodePudding user response:
You appear to want a pointer to the real element of a std::complex but are trying to convert a complex object to a pointer. They are entirely different things. Reinterpret_cast is very limited without UB but the standard makes an exception for std::complex
Check the dox as @Hajo suggests.
From: https://en.cppreference.com/w/cpp/numeric/complex
For any pointer to an element of an array of complex named p and any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i], and ....
You can do this leaving off []
as no the need to index into an array:
`double *d = reinterpret_cast<double*> (&c)`;
Caveat: While legal, if you change the value *d or c is changed you can get into UB. Generally a bad idea to do this.