Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding doubles and complex numbers in C++

Tags:

c++

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?

like image 767
bcf Avatar asked Jun 05 '15 00:06

bcf


People also ask

How do you add two complex numbers?

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.

Does C have support for complex numbers?

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).


1 Answers

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.

like image 121
Praetorian Avatar answered Sep 29 '22 10:09

Praetorian