Front Page / Tutorial: Metafunctions and Higher-Order Metaprogramming / Lambda Details / The Importance of Being Lazy

The Importance of Being Lazy

Recall the definition of always_int from the previous chapter:

struct always_int
{
    typedef int type;
};

Nullary metafunctions might not seem very important at first, since something like add_pointer<int> could be replaced by int* in any lambda expression where it appears. Not all nullary metafunctions are that simple, though:

typedef mpl::vector<int, char*, double&> seq;
typedef mpl::transform<seq, boost::add_pointer<_> > calc_ptr_seq;

Note that calc_ptr_seq is a nullary metafunction, since it has transform's nested ::type. A C++ template is not instantiated until we actually "look inside it," though. Just naming calc_ptr_seq does not cause it to be evaluated, since we haven't accessed its ::type yet.

Metafunctions can be invoked lazily, rather than immediately upon supplying all of their arguments. We can use lazy evaluation to improve compilation time when a metafunction result is only going to be used conditionally. We can sometimes also avoid contorting program structure by naming an invalid computation without actually performing it. That's what we've done with calc_ptr_seq above, since you can't legally form double&*. Laziness and all of its virtues will be a recurring theme throughout this book.