Is there a reason not to use unit enforcing types?
Asked Answered
O

2

6

Conceptually it seems to me that using unit enforcing based types (Meters, Seconds, Kilograms) would have massive benefits (extra checking in passing args, getting rid of unit names in vars, etc) and yet I've not run into as much code which does. And the code that I've seen that does has used custom types.

I see that boost has a units library (boost::units simply enough) and yet, I don't see much evidence of it being widely used (in a basic google search).

Is there a good reason for this?

Together these seem to imply that there must be some reason the practice has not been as widely adopted as I'd expect. Perhaps more trouble than they're worth for some reason?

And so I ask:

Is there a reason not to use unit enforcing types? And specifically is there are reason not to use boost::units?

Onder answered 25/9, 2012 at 16:24 Comment(0)
H
6

I think the main reason why this technique isn't more prevalent is that it's hideously difficult and cumbersome to spell out and to read.

Hopefully this will finally become a more accepted programming style with C++11, which adds user-defined literals to the language which let you write:

auto acc = 10_m / 1_s / 1_s;

rather than the traditional

myframework::units::si<acceleration>::type acc = myframework::unit_cast<units::meters>(10.0)
   / myframework::unit_cast<units::seconds>(1)
   / myframework::unit_cast<units::seconds>(1);
Heaton answered 25/9, 2012 at 16:28 Comment(4)
Oh, very nice. I wasn't aware of that feature in C++11.Onder
Couldn't a lot of that be resolved with a few typedefs though?Onder
@Catskul: You can't really get around a certain amount of verbosity. Have a look at Boost.Units and see how well a "professionally designed" solution fares. I'd say that's still a lot noisier than most programmers would be willing to put up with.Heaton
You "traditional example" could be simplified considerably quite easily by usage of typedefs and by not trying to do everything in one statement (use variables to hold the contributing values). True, there is always a certain amount of verbosity, but you are exaggerating how hard it is.Henley
H
3

I have used this library to great benefit for writing correct code. Unfortunately it's about 10 times harder to use than it should be. It's still worth it though as keeping track of dimensions and units is a nightmare.

The boost units library is very clever, powerful and complete. Problem is, the documentation is just about unreadable. There are lots of problems with confusing names, no type requirements. The authors included lot's of examples which are helpful - but not substitute for a better constructed document.

FYI - I presented a tutorial on this very subject at CPPcon 2015. You can find it at https://www.youtube.com/watch?v=qphj8ZuZlPA

Hagioscope answered 19/9, 2015 at 22:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.