现在我们很快就会有用户定义的文字 (UDL),例如在 GCC 4.7 中,我热切地等待(物理)单元库(例如 Boost.Units)使用它们来简化1+3i
、3m
、3meter
或 13_meter
等文字的表达。是否有人使用支持此行为的 UDL 编写了 Boost.Units 的扩展?
最佳答案
没有人提出这样的扩展。只有 gcc(可能还有 IBM?)有 UDL,所以可能需要一段时间。我希望某种单位能够进入 tr2,现在开始了。如果发生这种情况,我相信单位的 UDL 将会出现。
这个有效:
// ./bin/bin/g++ -std=c++0x -o units4 units4.cpp
#include <boost/units/unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
using namespace boost::units;
using namespace boost::units::si;
quantity<length, long double>
operator"" _m(long double x)
{ return x * meters; }
quantity<si::time, long double>
operator"" _s(long double x)
{ return x * seconds; }
int
main()
{
auto l = 66.6_m;
auto v = 2.5_m / 6.6_s;
std::cout << "l = " << l << std::endl;
std::cout << "v = " << v << std::endl;
}
我认为通过您最喜欢的单元并执行此操作不会太难。
关于将它们放入库中: 文字运算符是命名空间作用域函数。后缀的竞争将变得丑陋。我会(如果我是 boost)有
namespace literals
{
...
}
然后Boost用户可以做
using boost::units::literals;
连同您通常使用的所有其他 using decl。这样你就不会被 std::tr2::units
所破坏。同样,如果您自己滚动。
关于c++ - Physical Boost.Units 用户定义文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9257826/