This works:
#include <complex>
#include <iostream>
int main()
{
std::complex<double> z(0,2);
double n = 3.0; // Note, double
std::cout << z * n << std::endl;
}
Because complex is composed of doubles, it multiplies with doubles. Looking at the declaration:
template <typename T>
inline complex<T> operator*(const complex<T>&, const T&);
(The following is thanks to dribeas) The compiler is not allowed to make implicit type conversions during template deduction, so by passing a complex
with T being double
, and then another T being int
, when trying to match the function treating T as double
causes the second argument to mis-match, and vice-versa.
For what you want to work, it would have to have a function defined similar to this:
template <typename T, typename U>
inline std::complex<T> operator*(std::complex<T> lhs, const U& rhs)
{
return lhs *= rhs;
}
Which allows the function to take differing types, which allows the cast to be done when calling operator*=
.