【问题标题】:How to add your own base unit and conversions using boost::units如何使用 boost::units 添加您自己的基本单位和转换
【发布时间】:2011-10-03 20:04:34
【问题描述】:

我目前使用 boost::units 来表示以 si 为单位的扭矩,但是我得到了以磅英尺为单位的扭矩。因此,我试图创建一个 pound_foot 单位的扭矩和一个转换来支持这一点。我懒惰的尝试是简单地定义:

BOOST_STATIC_CONST(boost::si::torque, pound_feet = 1.3558179483314 * si::newton_meters);

然后做:

boost::si::torque torque = some_value * pound_feet;

但这感觉并不令人满意。我的第二次尝试是尝试定义一个名为 pound_foot 的新基本单位(见下文)。但是当我尝试以与上述类似的方式使用它时(对 si 单位进行强制转换),我得到一个充满错误的页面。对正确方法有什么建议吗?

namespace us {
  struct pound_foot_base_unit : base_unit<pound_foot_base_unit, torque_dimension> { };
    typedef units::make_system<
            pound_foot_base_unit>::type us_system;
    typedef unit<torque_dimension, us_system> torque;
    BOOST_UNITS_STATIC_CONSTANT(pound_foot, torque);
    BOOST_UNITS_STATIC_CONSTANT(pound_feet, torque);        
}
BOOST_UNITS_DEFINE_CONVERSION_FACTOR(us::torque, 
                                     boost::units::si::torque, 
                                     double, 1.3558179483314);

【问题讨论】:

    标签: c++ boost boost-units


    【解决方案1】:

    磅英尺并不是真正的基本单位,因此最好采用简洁的方式并根据基本单位(即英尺和磅)来定义它:

    #include <boost/units/base_units/us/pound_force.hpp>
    #include <boost/units/base_units/us/foot.hpp>
    #include <boost/units/systems/si/torque.hpp>
    #include <boost/units/quantity.hpp>
    #include <boost/units/io.hpp>
    #include <iostream>
    
    namespace boost {
    namespace units {
    namespace us {
    
    typedef make_system< foot_base_unit, pound_force_base_unit >::type system;
    typedef unit< torque_dimension, system > torque;
    
    BOOST_UNITS_STATIC_CONSTANT(pound_feet,torque);
    
    }
    }
    }
    
    using namespace boost::units;
    
    int main() {
        quantity< us::torque > colonial_measurement( 1.0 * us::pound_feet );
        std::cerr << quantity< si::torque >(colonial_measurement) << std::endl;
        return 0;
    }
    

    这个程序根据英尺和磅的已知值计算转换因子,输出为 1.35582 m^2 kg s^-2 rad^-1。不过请允许我对帝制的低劣嗤之以鼻。

    【讨论】:

    • 为什么要嘲笑帝制?这很有意义,有时每个子单元有 12 个单元,有时是 60 个,有时是 3 个。前缀的名称因事物类型而异。这是一个很棒的系统,你的冷笑是不受欢迎的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多