【问题标题】:Are bidirectional conversions by design or a bug?双向转换是设计使然还是错误?
【发布时间】:2012-11-29 18:05:25
【问题描述】:
#include <iostream>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>

using namespace boost::units;

struct bu1 : base_unit<bu1, length_dimension, 2001> {};
struct bu2 : base_unit<bu2, length_dimension, 2002> {};

BOOST_UNITS_DEFINE_CONVERSION_FACTOR(bu1, bu2, double, 1.5);

#if 1
BOOST_UNITS_DEFINE_CONVERSION_FACTOR(bu2, bu1, double, 4.0);
#endif

int main(int argc, char *argv[])
{
  quantity<bu1::unit_type> output(1 * bu2::unit_type());

  //  prints 4 or 0.67
  std::cout << output.value() << std::endl;

  return 0;
}

代码打印40.666667,具体取决于是否定义了第二个转换因子。这应该是设计使然吗?物理学中没有两个这样的单位需要不同的转换因子,是吗?

【问题讨论】:

    标签: c++ boost units-of-measurement boost-units


    【解决方案1】:

    这是一种垃圾输入/垃圾输出行为。您确实意识到 1.0 / 1.5 != 4.0,不是吗?第二个转换因子,如果要明确的话,应该是 (2.0/3.0),而不是 4。

    定义的第一个转换因子规范已经双向工作了。来自the documentation

    如果目标单位是一个基本单位或一个只包含一个基本单位的单位,该基本单位被提升到第一个幂(例如英尺->米),则不需要明确定义相反的(米->英尺)。

    有人可能会争辩说存在某种错误,它甚至允许您指定与第一个不一致的第二个转换因子。

    另外,我希望您在生产代码中使用 boost/units/io.hpp>,为您的单位指定名称/符号,而不是像 output.value() 这样的无量纲打印输出。我知道你的问题的方式更短,当然......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 2016-08-22
      • 2020-04-03
      • 1970-01-01
      • 2011-08-03
      • 2015-04-14
      • 2017-08-08
      • 2019-01-25
      相关资源
      最近更新 更多