Consider this bit of code:
#include <iostream>
#include <complex>
int main()
{
std::complex<double> z1 = 5;
std::cout << z1 - 1 << "\n"; // must change to z1 - 1.0 to compile
std::complex<int> z2 = 5;
std::cout << z2 - 1.0 << "\n"; // must change to z2 - 1 to compile
}
This produces a compilation error, as no operator-
is found for types in the expressions z1 - 1
or z2 - 1.0
. On the other hand, changing these expressions so that the base types match works fine.
Naively, for z1 - 1
I would expect the int
1 to be promoted to a double
, and expected the z2
, with base type int
, in z2 - 1.0
to be promoted to a complex<double>
. What's going on?
To add or subtract two complex numbers, just add or subtract the corresponding real and imaginary parts. For instance, the sum of 5 + 3i and 4 + 2i is 9 + 5i. For another, the sum of 3 + i and –1 + 2i is 2 + 3i.
The C programming language, as of C99, supports complex number math with the three built-in types double _Complex, float _Complex, and long double _Complex (see _Complex).
The operator-
you're trying to invoke is a function template with a single type template parameter.
template< class T >
complex<T> operator-( const complex<T>& lhs, const T& rhs);
Neither of the template parameters in the two function parameters appears in a non-deduced context, so template argument deduction is performed on both parameters individually, and this results in the T
for lhs
being deduced as double
, while that for rhs
is deduced as int
.
Due to this mismatch between the deduced types, template argument deduction fails, and your code doesn't compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With