THE BOOST MPL LIBRARY: Representing Quantities

Front Page / Tutorial: Metafunctions and Higher-Order Metaprogramming / Dimensional Analysis / Representing Quantities

# Representing Quantities

The types listed above are still pure metadata; to typecheck real computations we'll need to somehow bind them to our runtime data. A simple numeric value wrapper, parameterized on the number type `T` and on its dimensions, fits the bill:

    template <class T, class Dimensions>
    struct quantity
    {
        explicit quantity(T x)
           : m_value(x)
        {}

        T value() const { return m_value; }
     private:
        T m_value;
    };

Now we have a way to represent numbers associated with dimensions. For instance, we can say:

    quantity<float,length> l( 1.0f );
    quantity<float,mass> m( 2.0f );

Note that `Dimensions` doesn't appear anywhere in the definition of `quantity` outside the template parameter list; its only role is to ensure that `l` and `m` have different types. Because they do, we cannot make the mistake of assigning a length to a mass:

    m = l;    // compile-time type error