The C++ Boost Libraries (Part 2 - boost::assign)

Andrew Stephens, Sunday the 31st of May, 2009 in Computing

We are still only in the low lands of boost territory but already we are coming across useful discoveries . Today's stop is boost::assign, one of those clever little pieces of code that makes life easier for everyone. Often you just want to load up a container with some small amount of data. The STL containers do not make such a task particularly easy:

vector<string> faceCards;
faceCards.push_back("jack");
faceCards.push_back("queen")
faceCards.push_back("king");
faceCards.push_back("ace");

What a pain in the neck! With boost::assign it becomes:

vector<string> faceCards;
faceCards += "jack","queen", "king", "ace";

Neat.

It gets better. A lot of the time you want to fill a container with some data for testing but you don't really care what that data is:

list<int> data;
// data will contain 1,2,5,5,5,5,5,5,5,5,7
data += 1, 2, repeat(8, 5), 7;

Or even:

list<int> randomData;
// data will contain 1,2,(8 random numbers),7
randomData += 1, 2, repeat_fun(8, &rand),7;

Of course, other containers are supported. This example uses the more flexible insert function (there are other functions for inserting at specific points for containers that support such things):

map<string, string> maoriColors;
insert(maoriColors)("ma", "white")
                   ("whero", "red")
                   ("kakariki", "green")
                   ("kowhai", "yellow" );

As with all the boost libraries, a lot of thought has gone into to making the interface safe and flexible. The library can even be extended to non-standard containers if the need should arise.

All the best magic tricks are really just smoke and mirrors, boost::assign is really just functions that secretly return functor objects and operator,() abuse. Unlike most magic, knowing how it works makes it even more delightful; the library is very well documented.

Although boost::assign is useful anywhere, it really shines in simple throwaway programs and test harnesses, where small, simple and easily modifiable code is the goal. I keep finding more and more places to use it.