C++ 将标量乘以boost.units.quantity(自动类型转换问题?)
这是一个非常简单的例子。我以以下方式使用Boost.Units:C++ 将标量乘以boost.units.quantity(自动类型转换问题?),c++,boost,boost-units,C++,Boost,Boost Units,这是一个非常简单的例子。我以以下方式使用Boost.Units: #define REAL double ... using namespace boost::units; quantity<si::velocity, REAL> v; 查看Boost.Units我发现操作符*过载如下: // runtime scalar times quantity template<typename Unit, typename X> multiply_typeof_hel
#define REAL double
...
using namespace boost::units;
quantity<si::velocity, REAL> v;
查看Boost.Units我发现操作符*
过载如下:
// runtime scalar times quantity
template<typename Unit, typename X>
multiply_typeof_helper< X, quantity< Unit, X > >::type
operator*(const X & lhs, const quantity< Unit, X > & rhs);
//运行时标量乘以数量
模板
乘法\u-typeof\u-helper>::type
操作员*(常数X和左手,常数数量<单位,X>和右手);
虽然从定义中可以清楚地看出,数量的标量和内部类型必须相同,但我希望编译器在可以隐式地进行转换时自动转换类型(如从double
到long double
)。然而,我认为我可能遗漏了一些东西,因为自动类型转换肯定适用于其他简单函数,如longdoulf(longdoupleconst&ld)
我的问题是,我使用了很多表达式,比如v_halved=0.5*v
,我的项目已经相当大了,直到现在,在不得不将REAL
定义为long double
之后,我才意识到这是一个问题。所以,我想知道一个解决方法/解决方案,我知道static\u cast(0.5)
将是一个解决方案,但我仍然觉得编译器无法自动将标量转换为正确的类型
提前多谢 模板函数与非模板函数不同。编译器决定选择模板函数而不考虑隐式转换/升级。它只是寻找精确的匹配 <>这是C++在这个领域的工作原理。< /P> 要获得精确的匹配,您需要这样的
运算符*
定义(注意这个额外的模板参数):
模板
typename multiply\u typeof\u helper>::type
内联运算符*(常数Y和lhs,常数数量<单位,X>和rhs)
{
返回静态_型铸造(lhs)*rhs;
}
但我担心这会干扰*
的boost定义。你可以使用这个-比如定义你自己的数量
,它几乎完全来自boost-但是我建议用不同的方式定义乘法
只要决定什么对你来说更容易
- 执行静态强制转换(或者最好只添加
-L
以使长双常量)0.5L
- 或者与模板进行一些组合李>
操作符*
的新定义可能会干扰原始定义,因此这可能是库作者的决定。然后我想我会坚持使用static\u cast
解决方案,因为使用0.5L
将是特定于类型的。
error: no match for ‘operator*’ in ‘5.0e-1 * v’
/usr/include/boost/units/detail/one.hpp:58: note: candidates are: boost::units::one boost::units::operator*(const boost::units::one&, const boost::units::one&)
// runtime scalar times quantity
template<typename Unit, typename X>
multiply_typeof_helper< X, quantity< Unit, X > >::type
operator*(const X & lhs, const quantity< Unit, X > & rhs);
template<typename Unit, typename X, typename Y>
typename multiply_typeof_helper< X, quantity< Unit, X > >::type
inline operator*(const Y & lhs, const quantity< Unit, X > & rhs)
{
return static_cast<X>(lhs) * rhs;
}