Return type based on input value

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

The following is an example of my first attempt, however this will not compile due to the presence ain 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));
    }
}
+2
source share
3 answers

No, It is Immpossible.

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

constexpr ", . .

+5

boost::variant<double, std::complex<double>> ( ), .

+2

, , , , , , .

, . , , , X + 0i (.. 0).

, , sqrt . , , , , , NaN - . ( ) , .

+2
source

Source: https://habr.com/ru/post/1682776/


All Articles