[Effective-cpp] Item 48: Be aware of template metaprogramming

Erik Haugen haugen at gmail.com
Wed Oct 25 21:01:27 EDT 2006


On 10/25/06, Frances Buontempo <frances.buontempo at gmail.com> wrote:
>
>
>
> On 23/10/06, Giles <agander at gmail.com> wrote:
> > Other items referenced: 47 and 2, 35, 44, 54, 55.
> >
> > TMP is "Turing Complete". i.e. It is "powerful enough to compile
> anything". In
> > practise this means that you can declare variables, perform loops and
> > write/call functions.
>
>
> Should that be "powerful enough to perform any computation at compile time"
> rather than compile anything? I've seen loads of code that won't compile,
> and not just code I've written!
> And surely most languages are Turing complete anyway, including C++. Isn't
> it 'just' saying, for example, anything you can compute at runtime in C++
> you could compute at compile time with TMP?
>
> >
> > Scientific and Engineering
> >
> > In scientific and engineering applications it is possible during
> compilation
> > to ensure that dimentional  units are correct. So, for instance, a
> variable
> > representing mass is not used in place of one for  velocity.
>
>
> Can anyone give a code example of this? I can't figure one out. I guess
> something like traits, but I'd still be happier with an example.
>
>
> Regards,
> Frances.

Scott is likely thinking of this:
http://www.artima.com/cppsource/metafunctions.html

If you don't feel like following the link, this snippet may give you
an idea of what it's about:

typedef mpl::vector_c<int,1,0,0,0,0,0,0> mass;
typedef mpl::vector_c<int,0,1,0,0,0,0,0> length; // or position
typedef mpl::vector_c<int,0,0,1,0,0,0,0> time;
typedef mpl::vector_c<int,0,0,0,1,0,0,0> charge;
typedef mpl::vector_c<int,0,0,0,0,1,0,0> temperature;
typedef mpl::vector_c<int,0,0,0,0,0,1,0> intensity;
typedef mpl::vector_c<int,0,0,0,0,0,0,1> angle;

typedef mpl::vector_c<int,0,0,0,0,0,0,0> scalar;

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

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

So now a quantity uses one of these vector_c's as Dimension, and T is
probably float or something.

quantity<float,length> len1( 1.0f );

Then there are various techniques for making sure you don't perform
operations such as addition unless the Dimensions template params are
compatible.



More information about the Effective-cpp mailing list