Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Physical Boost.Units User Defined Literals

Now that we soon have user defined literals (UDL), in GCC 4.7 for example, I'm eagerly waiting for (physical) unit libraries (such as Boost.Units) using them to ease expression of literals such as 1+3i, 3m, 3meter or 13_meter. Has anybody written an extension to Boost.Units using UDL supporting this behaviour?

like image 638
Nordlöw Avatar asked Feb 13 '12 09:02

Nordlöw


1 Answers

No one has come out with such an extension. Only gcc (and possibly IBM?) has UDL so it might be a while. I'm hoping some kind of units makes it into tr2 which is starting about now. If that happens I'm sure UDL for units will come up.

This works:

//  ./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;
}

I think it wouldn't be too hard to go through you favorite units and do this.

Concerning putting these in a library: The literal operators are namespace scope functions. The competition for suffixes is going to get ugly. I would (if I were boost) have

namespace literals
{
...
}

Then Boost users can do

using boost::units::literals;

along with all the other using decls you typically use. Then you won't get clobbered by std::tr2::units for example. Similarly if you roll your own.

like image 151
emsr Avatar answered Sep 18 '22 12:09

emsr