代码之家  ›  专栏  ›  技术社区  ›  allo

让C++自动转换int到双

  •  3
  • allo  · 技术社区  · 6 年前

    当我有一个数字类型时,它定义了 operator< 对于double,而不是int,与int文本比较不起作用。这是一个问题,作为标准库的一部分,即 std::complex 包含int文本。

    我可以让编译器在使用类型时将int文本视为双精度文本吗?

    简化示例:

    // the defined operator
    template<typename T>
    bool operator<(const Type<T> &lhs, const T &rhs);
    
    complex<Type<T>> complex_number;
    1.0 / complex_number; // this fails
    

    故障发生在 _Div 方法 STD::复合物

    template<class _Other> inline
    void _Div(const complex<_Other>& _Right)
        // ...
        else if ((_Rightimag < 0 ? -_Rightimag : +_Rightimag)
    

    导致错误:

    error C2678: binary '<': no operator found which takes a left-hand operand of type 'Type<T>' (or there is no acceptable conversion)
    (...)
    complex(665): note: while trying to match the argument list '(Type<T>, int)'
          [
              T=double
          ]
    

    我想可能是密码 STD::复合物 应该是 _Rightimag < static_cast<_Other>(0) 要处理所有数字类型,但我必须处理stdlib提供的内容。

    由于另一种类型也来自库,所以我正在寻找一种方法来将隐式转换添加到代码中。


    对于实际代码:我正在使用 ceres ,这使您可以使用模板化标量类型为自动差异定义函数。标量都计算为 T 作为 Jet<T, N> .

    谷神星 defines operator<(const Jet<T, N>&, const T&) ,允许 jet < 0.0 但不是为了 jet < 0 .

    在我的代码中,我可以通过使用double或显式地将整数强制转换为模板类型来解决这个问题。 T 但是当我尝试与 complex<T> 对于与整型文字进行比较的方法,比如 第二乐章 以上方法。

    2 回复  |  直到 6 年前
        1
  •  5
  •   aschepler    6 年前

    这个 std::complex 使用常规类型不需要模板。标准规定[复数]/2:

    实例化模板的效果 complex 对于除 float , double long double 未指定。

    如果需要将任何其他类似于数字的类型归纳为类似复杂的类型,则应使用其他库或实现自己的库。

        2
  •  0
  •   Tim Randall    6 年前

    是的,您可以通过定义一个接受单个参数(您要转换的类型)的构造函数来获得隐式转换。