What is the best way to cast in C++? [closed]
What is the best way to cast from complex
to int
in C++?
It's difficult to answer your question since there isn't, in general, a way to do this. Mathematically speaking, what does it mean to cast a complex number (a + bi) to a real number (a + 0i)? You could drop the complex term, or restrict yourself to the case where b = 0, I suppose; this first option seems inelegant and the second option doesn't always work.
The second problem you'll have to address is that in C++ the complex
template exists for float
, double
, and long double
, none of which have lossless conversions to int
. So I suppose that if you work out the details of the first part, you'd then have to ensure that the rest of the cast is still valid.
If what you want to do is extract the real component from a complex
, you can do this:
complex<double> myComplex = /* ... */
double real = myComplex.real();
and then possibly
int realInt = static_cast<int>(real);
You can overload operator int ();
精彩评论