Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Why can't I construct a quantity directly from the value type?

This only breaks generic code--which ought to break anyway. The only literal value that ought to be converted to a quantity by generic code is zero, which should be handled by the default constructor. In addition, consider the search and replace problem allowing this poses:

quantity<si::length>    q(1.0);

Here, the intent is clear - we want a length of one in the SI system, which is one meter. However, imagine some well-intentioned coder attempting to reuse this code, but to have it perform the calculations in the CGS unit system instead. After searching for si:: and replacing it with cgs:: , we have:

quantity<cgs::length>	q(1.0);

Unfortunately, the meaning of this statement has suddenly changed from one meter to one centimeter. In contrast, as implemented, we begin with:

quantity<si::length>	q(1.0*si::meter);

and, after search and replace:

quantity<cgs::length>	q(1.0*cgs::meter);

which gives us an error. Even if the code has a @using namespace boost::units::si; declaration, the latter is still safe, with:

using namespace boost::units::si;
quantity<length>	q(1.0*meter);

going to

using namespace boost::units::cgs;
quantity<length>	q(1.0*meter);

The latter will involve an explicit conversion from meters to centimeters, but the value remains correct.


PrevUpHomeNext