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

StackOverflow https://stackoverflow.com/questions/22919357

  •  29-06-2023
  •  | 
  •  

Question

I'm 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 it using MingW 4.5.2, and I receive the error: no match found for 'operator[]'. I really need to use the [] operator for now, because otherwise I would have to change hundreds of lines of code.

Was it helpful?

Solution 2

Nope.

You could derive from std::complex<> and inherit constructors and add an overridden operator[], but I would advise against it.

OTHER TIPS

As per here in C++11:

For any object z of 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 of z.

For any pointer to an element of an array of 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 can't do this with a std::complex<T> but if you really have to you can reinterpret_cast to a T* or T(&)[2] and use operator[] on that.

If possible, I would suggest creating an accessor 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) where needed.

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 for getting the results of operations/functions involving std::complex as Complex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top