简体   繁体   中英

Casting std::complex<double> as double

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?

double d = c.real();

Best read the documentation of std::complex before continuing to use it:

https://en.cppreference.com/w/cpp/numeric/complex

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM