在我看来,为 Boost.Units 使用字面量并没有太大的好处,因为使用现有功能仍然可以实现更强大的语法。
在简单的情况下,看起来像文字是要走的路,但很快你就会发现它不是很强大。
例如,您仍然需要为组合单位定义字面量,例如,如何表示 1 m/s(一米每秒)?
目前:
auto v = 1*si::meter/si::second; // yes, it is long
但是使用文字?
// fake code
using namespace boost::units::literals;
auto v = 1._m_over_s; // or 1._m/si::second; or 1._m/1_s // even worst
可以利用现有功能实现更好的解决方案。这就是我所做的:
namespace boost{namespace units{namespace si{ //excuse me!
namespace abbreviations{
static const length m = si::meter;
static const time s = si::second;
// ...
}
}}} // thank you!
using namespace si::abbreviations;
auto v = 1.*m/s;
您可以使用相同的方式:auto a = 1.*m/pow<2>(s); 或根据需要扩展缩写(例如 static const area m2 = pow<2>(si::meter);)
你还想要什么?
也许组合解决方案可能是这样的方式
auto v = 1._m/s; // _m is literal, /s is from si::abbreviation combined with operator/
但是会有这么多的冗余代码,收益微乎其微(在数字后面用_替换*。)
我的解决方案的一个缺点是它使用常见的一个字母名称来污染命名空间。但除了在1.*m_/s_ 中添加下划线(在缩写的开头或结尾)之外,我没有看到解决方法,但至少我可以构建真正的单位表达式。