Santi Peñate-Vera
Santi Peñate-Vera

Reputation: 1186

std::complex<double> multiplication by other types

I have the following instructions in C++:

std::complex<double> c(1.0, 1.0);
bool b = true;
double a = 1.0;
int f = 1;

double d = a * b;
double e = b * c;  // this operation (bool x complex) is not available    
double g = f * c;  // this operation (int x complex) is not available 

Observe that the complex<double> cannot be multiplied by an int not by a bool type.

I read somewhere that this was to be solved by the C++ 20 standard. But, in the mean time

How can I solve this?

Can I overload something so that the compiler understands these operations?

I do not want to declare everything as a complex<double>, and I do not want to program functions to pass arguments because my aim is to use the Armadillo C++ library which uses complex<double> for their complex matrices and I want to be able to multiply a complex matrix by a bool matrix. That is why I cannot use functions, but should rather use some kind of class extension / overloading.

Upvotes: 0

Views: 821

Answers (2)

Santi Pe&#241;ate-Vera
Santi Pe&#241;ate-Vera

Reputation: 1186

This is it:

complex<double> operator * (const int & a, const complex<double> & b){
    if (a != 0)
        return complex<double>(b.real() * a, b.imag() * a);
     else
        return complex<double>(0, 0);
}

By putting this function around, the compiler understands the operation. Also did the trick with Armadillo C++ matrices.

Upvotes: 0

cigien
cigien

Reputation: 60218

Yes, you can simply provide overloads for operator*, like this:

double operator*(bool, std::complex<double>);

double operator*(int, std::complex<double>);

Obviously, you need to write the definitions as well.

Upvotes: 1

Related Questions