gpt4 book ai didi

c++ - 使C++自动将int转换为double

转载 作者:太空狗 更新时间:2023-10-29 20:33:54 26 4
gpt4 key购买 nike

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

我能否让编译器在使用该类型时将 int 字面量视为 double?

简化示例:

// 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::complex的方法|在

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::complex中的代码应该是 _Rightimag < static_cast<_Other>(0)使用所有数字类型,但我必须使用 stdlib 提供的内容。

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


对于实际代码:我正在使用 ceres ,它允许您使用用于自动微分的模板化标量类型定义仿函数。标量均被评估为 TJet<T, N> .

谷神星 defines operator<(const Jet<T, N>&, const T&) , 这允许 jet < 0.0但不适用于 jet < 0 .

在我的代码中,我可以通过使用 double 或将整数显式转换为模板类型 T 来解决该问题。 ,但是当我尝试使用 complex<T> 时我遇到了与整数文字进行比较的方法的麻烦,比如 _Div以上方法。

最佳答案

std::complex 模板不需要处理通用类型。标准说 [complex.numbers]/2:

The effect of instantiating the template complex for any type other than float, double, or long double is unspecified.

如果您需要将任何其他类似数字的类型泛化为类似复杂的类型,您应该使用一些不同的库或实现您自己的库。

关于c++ - 使C++自动将int转换为double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com