Re: Overload = and [ ] to store complex value terms in class
jwest wrote:
I am writing a class to wrap around a C numerical routine that processes
the real and imaginary parts of complex data in two different arrays.
The wrapper I have so far is
class COMPLEX_DATA {
std::valarray<std::complex<double> > real_data, imag_data;
I assume you really mean
std::valarray<double> real_data, imag_data;
public:
// (functions that call the C-code to process)
}
In order to make access to this class as transparent as possible within
our C++ code, I would like to overload equal sign and [ ] operators so
we can both read from and write to the internal valarrays directly from a
complex variable. That is, I would like to be able to do the following
COMPLEX_DATA d_c;
std::complex<double> a, b;
// Set a to the value std::complex<double>(d_c.real_data[i], d_c.imag_data[i])
// using
a = d_c[i];
// Set d_c.real_data[i] = real(b) and d_c.imag_data[i] = imag(b) using
d_c[i] = b;
The first one is easy, but the second one is unfortunately beyond my
abilities (if it is even possible). Can anyone enlighten me?
OK - here is an example using a proxy class.
#include <complex>
#include <valarray>
class COMPLEX_DATA {
std::valarray<double> real_data, imag_data;
public:
COMPLEX_DATA(std::size_t size)
: real_data(size), imag_data(size)
{}
class adaptor {
COMPLEX_DATA & v;
const std::size_t index;
public:
adaptor( COMPLEX_DATA & v, std::size_t index )
: v(v), index(index) {}
adaptor & operator = ( const std::complex<double> & val ) const
{
v.real_data[index] = val.real();
v.imag_data[index] = val.imag();
}
operator std::complex<double> () const
{
return std::complex<double>(
v.real_data[index], v.imag_data[index] );
}
};
const std::complex<double> operator[](std::size_t index) const
{
return std::complex<double>( real_data[index], imag_data[index]);
}
const adaptor operator[](std::size_t index)
{
return adaptor(*this, index);
}
};
void f(COMPLEX_DATA & d)
{
std::complex<double> v(1,1);
d[2] = v;
v = d[2];
}
void y(const COMPLEX_DATA & d)
{
std::complex<double> v(1,1);
// d[2] = v; -- error - can't assign to const
v = d[2];
}
COMPLEX_DATA d(std::size_t(30));
int main()
{
f(d);
y(d);
}