[英]Make C++ automatically convert int to double
当我有一个数字类型,它定义operator<
for double,但不是int,与int literals的比较不起作用。 这是一个问题,因为标准库的一部分,即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
失败发生在std::complex
at的_Div
方法中
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 ,它允许您使用模板化标量类型定义仿函数以进行自动分化。 标量都被评估为T
和Jet<T, N>
。
Ceres 定义了 operator<(const Jet<T, N>&, const T&)
,它允许jet < 0.0
但不允许jet < 0
。
在我的代码中,我可以通过使用双精度或明确地将整数转换为模板类型T
来解决问题,但是当我尝试使用complex<T>
我遇到了与整数文字进行比较的方法的麻烦,比如_Div
方法以上。
std::complex
模板不需要使用常规类型。 标准说[complex.numbers] / 2:
未指定将
float
,double
或long double
以外的任何类型实例化模板complex
的效果。
如果您需要将任何其他类似数字的类型概括为类似复杂的类型,那么您应该使用一些不同的库或实现自己的库。
是的,您可以通过定义一个带有单个参数(您要转换的类型)的构造函数来获得隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.