Is it possible to access the real and imaginary parts of a complex number using the [] operator in C ++

I am using the <complex> library in C ++. Is it possible to access the real and complex parts of a complex number using the [] operator? I want to use myComplexNum[0] instead of myComplexNum.real() and myComplexNum[1] instead of myComplexNum.imag() .

I tried to do this with MingW 4.5.2, and we get an error: no match found for 'operator[]' . I really need to use the [] operator, because otherwise I would have to change hundreds of lines of code.

+1
c ++ std complex-numbers
source share
3 answers

Nope.

You can get from std::complex<> and inherit the constructors and add an overridden operator[] , but I would advise doing this.

+2
source share

According here in C ++ 11:

For any object z type complex<T> , reinterpret_cast<T(&)[2]>(z)[0] is the real part of z and reinterpret_cast<T(&)[2]>(z)[1] is the imaginary part z .

For any pointer to an array element complex<T> named p and any valid array index i , reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i] , and reinterpret_cast<T*>(p)[2*i + 1] is the imaginary part of the complex number p[i]

You cannot do this with std::complex<T> , but if you really need to reinterpret_cast on T* or T(&)[2] and use operator[] on this.

If possible, I would suggest creating an access function:

  template <class T> T & get(std::complex<T> & c, int index) { if(index == 0) return c.real(); else return c.imag(); } 

and then use get(c, 0) and get(c, 1) if necessary.

+3
source share

You will have to wrap std :: complex in your complex class:

 class Complex { public: explicit Complex(std::complex& value) : m_value(value) {} ... operator std::complex& () { return m_value; } operator const std::complex& () const { return m_value; } ... private: std::complex m_value; } 

This will be necessary to obtain the results of operations / functions involving std :: complex as Complex.

+1
source share

All Articles