基于输入参数值的返回类型 [英] Return type based on value of input parameter

查看:71
本文介绍了基于输入参数值的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,有一种方法可以实现 sqrt 函数,该函数可用于正负两个 double 输入值?我希望返回类型为 std :: complex< double> 如果输入为负,则为 double 这是积极的。我知道简单的解决方案是始终返回 std :: complex< double> ,但这不是我想要的。

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.

下面有一个第一次尝试的示例,但是由于返回类型中存在 a ,因此无法编译:

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));
    }
}


推荐答案

否,这是不可能的。

类型是编译时构造,函数的类型固定在编译时。

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

如果将参数作为 constexpr 常量表达式提供,那么您可能已使用模板来解决问题。但是,使用动态输入是不可能的。

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.

这篇关于基于输入参数值的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆