On 13 Apr 2006 20:34:31 -0700, "vj" <vi**********@gmail.com> wrote:

r = -cc/(sqrt(cc*cc-detuning*detuning)* // more code ...
... But even if I am taking sqrt of

a negative number, the result will be a complex number, and the 'r' has

been declared as a complex number, so shouldn't the code be able to

handle this?

Overloading is a great strength of C++, but it can lead the unwary

astray. sqrt is an identifier that refers to a small family of

overloaded functions. The process of overload resolution picks one of

these functions for the operation in your code.

First all the possible candidate functions for the overload are

identified. Inclusion of proper headers may affect such

identification. In this case, the list should include sqrt(double),

sqrt(float), sqrt(long double), sqrt(complex<double>), etc.

Then of those candidates, the best function (if unique) is chosen by a

series of rules based on the number and types of the arguments. Note

that the return type of the function is of no importance in this

process.

In your case, the argument is of type double, so the real-valued

sqrt(double) will be chosen. To chose the complex valued sqrt, you

need to finagle the argument type.

As I see it, there are three ways to handle this problem.

First, if mixing doubles and complex types is a recurring theme in the

program, I would probably write an inline function to cover the

conversion, say, something like this:

inline std::complex<double> mysqrt(double t)

{

return sqrt(static_cast<std::complex<double> >(t));

}

Call it what you like, but mysqrt(-4) will invoke the complex form.

Second, if the answer is a complex number, make all the variables

complex from the start by changing all the double variables to

complex. Overload resolution works best by sticking to one type of

number.

Third, if mixing doubles and complex types is rare, then explicitly

cast the double when a complex function needs to be invoked.

HTH.

--

Best wishes,

Bob