The following code has type casting error
#define IMG_I (std::complex<double>(0, 1))
#define PI 3.1415926535
for (unsigned long int j = 0; j < 10; ++j)
std::cout << exp(-IMG_I * PI * j);
The type casting can be easily solved by using extra parenthesis or changing the order of multiplication. But it is not clear for me why the type casting problem occurs in the first place and why the c++ cannot handle the above code as it is.
can anyone explain this for me?
This
operator*overload forstd::complexis a function template with a declaration that looks like:The
Tincomplex<T>for thelhsargument must be the same as theTfor thevalargument in order for template argument deduction to work.You are trying to call it with a
std::complex<double>(the type of-IMG_I * PI) and anunsigned long(the type ofj).doubleandunsigned longare not the same type, so template argument deduction fails.-IMG_I * (PI * j)works because the type ofPI * jisdouble, so there is no ambiguity as to whatTis. Likewise,-IMG_I * PI * static_cast<double>(j)works for the same reason.