Вопрос

In C++11 is there a way to implement a sqrt function that works for both positive and negative double input values? I would like the return type to be std::complex<double> if the input is negative and a double if it is positive. I realize the simple solution is to just always return std::complex<double> but this is not what I am looking for.

Below I have an example of my first attempt, however this does not compile due to the presence of a in the return type:

inline decltype((a > 0)?(double):(std::complex<double>)) sqrt(const double& a)
{
    if(a > 0)
    {
        return std::sqrt(a);
    }
    else
    {
        return ((std::complex<double>(0.0,1.0))*std::sqrt(-a));
    }
}
Это было полезно?

Решение

No, this is not possible.

Types are compile-time constructs, and your function's type is fixed at compile-time.

Were the argument provided as a constexpr "constant expression", then you might have used templates to solve your problem. But, with dynamic inputs, this is simply not possible.

Другие советы

You could return a boost::variant<double, std::complex<double>> (since the decision has to be made at runtime), but that seems like adding a lot of complexity to your code for no real gain.

It's not possible, and probably more importantly, probably wouldn't be useful even if you could do it.

Since the function can return a complex number, the calling code needs to be prepared to process a complex number. If your code needs to be able to process complex numbers in any case, it almost certainly makes more sense to always return a complex number, and if the input was positive it'll be of the form X + 0i (i.e., the imaginary part will equal 0).

In theory, you could do this in a language that supported dynamic typing -- but even with most of them, sqrt is basically statically typed. If the input you provide is a real number, the result will also be a real number, and if the input was negative the result will typically be a NaN or something on that order. If (and only if) you provide the input as a complex number will you receive a complex number as the result.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top