Return type based on the value of the input parameter

advertisements

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.