views:

153

answers:

2

The following code fails to compile

#include <iostream>
#include <cmath>
#include <complex>

using namespace std;

int main(void)
{
    const double b=3;
    complex <double> i(0, 1), comp;

    comp = b*i;

    comp = 3*i;

    return 0;
}

with error: no match for ‘operator*’ in ‘3 * i’ What is wrong here, why cannot I multiply with immediate constants? b*i works.

+3  A: 

See http://www.cplusplus.com/reference/std/complex/complex/operators/ for an overview of the complex operators.

You will notice that the operator* is a template and will use the template parameter of the complex class to generate that code. The number literal you use to invoke operator* is of type int. Use comp = 3. * i;

pmr
+3  A: 

In the first line:

comp = b*i;

The compiler calls:

template<class T> complex<T> operator*(const T& val, const complex<T>& rhs);

Which is instanced as:

template<> complex<double> operator*(const double& val, const complex<double>& rhs);

In the second case, there is no appropriate template int, so the instancing fails:

comp = 3.0 * i; // no operator*(int, complex<double>)
greyfade