Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Assignment Library

Copyright © 2003-2006 Thorsten Ottosen

Use, modification and distribution is subject to the Boost Software License, Version 1.0 (see http://www.boost.org/LICENSE_1_0.txt).

Table of Contents


Introduction

There appear to be few practical uses of operator,().
Bjarne Stroustrup, The Design and Evolution of C++

The purpose of this library is to make it easy to fill containers with data by overloading operator,() and operator()(). These two operators make it possible to construct lists of values that are then copied into a container:

These lists are particularly useful in learning, testing, and prototyping situations, but can also be handy otherwise. The library comes with predefined operators for the containers of the standard library, but most functionality will work with any standard compliant container. The library also makes it possible to extend user defined types so for example a member function can be called for a list of values instead of its normal arguments.


Tutorial

Within two minutes you should be able to use this library. The main components are explained in these sections:

The two first functions are used for adding elements after a container object has been created whereas the next two is used when we need to initialize an object.

Function operator+=()

To fill a vector (or any standard container) with values using operator+=() you write

#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope

{
    vector<int> values;  
    values += 1,2,3,4,5,6,7,8,9; // insert values at the end of the container
    BOOST_ASSERT( values.size() == 9 );
    BOOST_ASSERT( values[0] == 1 );
    BOOST_ASSERT( values[8] == 9 );
}
Here we only stuffed constants into the container, but the list can consists of arbitrary expressions as long as the result of each expression is convertible to the value_type of the container.

Function operator()()

We do not call operator()() directly, but instead we call a function that returns a proxy-object that defines operator()(). The function that returns the proxy object is always named after the member function that is used to copy the values in the list into the container. So to fill a map with pairs of values you write

#include <boost/assign/list_inserter.hpp> // for 'insert()'
#include <boost/assert.hpp> 
#include <string>
using namespace std;
using namespace boost::assign; // bring 'insert()' into scope
 
{
    map<string,int> months;  
    insert( months )
        ( "january",   31 )( "february", 28 )
        ( "march",     31 )( "april",    30 )
        ( "may",       31 )( "june",     30 )
        ( "july",      31 )( "august",   31 )
        ( "september", 30 )( "october",  31 )
        ( "november",  30 )( "december", 31 );
    BOOST_ASSERT( months.size() == 12 );
    BOOST_ASSERT( months["january"] == 31 );
} 
Note that operator()() is much more handy when we need to construct objects using several arguments (up to five arguments are supported by default, but the limit can be
customized). This is also true for sequences:
#include <boost/assign/list_inserter.hpp> // for 'push_front()'
#include <boost/assert.hpp> 
#include <string>
#include <utility>
using namespace std;
using namespace boost::assign; // bring 'push_front()' into scope
 
{
    typedef pair< string,string > str_pair;
    deque<str_pair> deq;
    push_front( deq )( "foo", "bar")( "boo", "far" ); 
    BOOST_ASSERT( deq.size() == 2 );
    BOOST_ASSERT( deq.front().first == "boo" );
    BOOST_ASSERT( deq.back().second == "bar" );
}   
Besides push_front() we could also have used push_back() if the container has a corresponding member function. Empty parentheses can be used to insert default-constructed objects, for example, push_front( deq )()() will insert two default-constructed str_pair objects.

If operator()() is too cumbersome to use with eg. push_front()we can also say

deque<int> di;    
push_front( di ) = 1,2,3,4,5,6,7,8,9;
BOOST_ASSERT( di.size() == 9 );    
BOOST_ASSERT( di[0] == 9 );    

Just to make it perfectly clear, the code above is not restricted to the standard containers, but will work with all standard compliant containers with the right member function. It is only operator+=() that has been restricted to the standard containers.

Function list_of()

But what if we need to initialize a container? This is where list_of() comes into play. With list_of() we can create anonymous lists that automatically converts to any container:
#include <boost/assign/list_of.hpp> // for 'list_of()'
#include <boost/assert.hpp> 
#include <list>
#include <stack>
#include <string>
using namespace std;
using namespace boost::assign; // bring 'list_of()' into scope
 
{
    const list<int> primes = list_of(2)(3)(5)(7)(11);
    BOOST_ASSERT( primes.size() == 5 );
    BOOST_ASSERT( primes.back() == 11 );
    BOOST_ASSERT( primes.front() == 2 );
   
    const stack<string> names = list_of( "Mr. Foo" )( "Mr. Bar")( "Mrs. FooBar" ).to_adapter();
    const stack<string> names2 = (list_of( "Mr. Foo" ), "Mr. Bar", "Mrs. FooBar" ).to_adapter();
    BOOST_ASSERT( names.size() == 3 );
    BOOST_ASSERT( names.top() == "Mrs. FooBar" );
}   
If we need to initialize a container adapter, we need to help the compiler a little by calling to_adapter(). As the second example also shows, we can use a comma-separated list with list_of() if we add parenthesis around the entire right hand side. It is worth noticing that the first argument of list_of() determines the type of the anonymous list. In case of the stack, the anonymous list consists of const char* objects which are then converted to a stack of string objects. The conversion is always possible as long as the conversion between the stored types is possible.

Please notice that list_of() can even convert to a boost::array<T,sz> and see also the list of supported libraries .

Note that the type returned by list_of() (and its variants) has overloaded comparison operators. This allows you to write test code such as BOOST_CHECK_EQUAL( my_container, list_of(2)(3)(4)(5) );.

Function map_list_of()

This function is defined for pure convenience when working with maps. Its usage is simple:
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/assert.hpp> 
#include <map>
using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope
 
{
    map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
    BOOST_ASSERT( next.size() == 5 );
    BOOST_ASSERT( next[ 1 ] == 2 );
    BOOST_ASSERT( next[ 5 ] == 6 );
    
    // or we can use 'list_of()' by specifying what type
    // the list consists of
    next = list_of< pair<int,int> >(6,7)(7,8)(8,9);
    BOOST_ASSERT( next.size() == 3 );
    BOOST_ASSERT( next[ 6 ] == 7 );
    BOOST_ASSERT( next[ 8 ] == 9 );      
}   
The function pair_list_of() may also be used.

Function tuple_list_of()

If you are working with tuples, it might be convenient to use tuple_list_of():
#include <boost/assign/list_of.hpp>
#include <vector>

using namespace std;
using namespace boost::assign;

{
    typedef boost::tuple<int,std::string,int> tuple;

    vector<tuple> v = tuple_list_of( 1, "foo", 2 )( 3, "bar", 4 );
    BOOST_CHECK( v.size() == 2 );
    BOOST_CHECK( boost::get<0>( v[1] ) ==  3 );
}
    

Functions repeat(), repeat_fun() and range()

Sometimes it is too irritating to repeat the same value many times. This is where repeat() can be handy:

#include <boost/assign/list_of.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/assert.hpp>

using namespace std;
using namespace boost::assign;
 
{
    vector<int> v;
    v += 1,2,3,repeat(10,4),5,6,7,8,9;
    // v = [1,2,3,4,4,4,4,4,4,4,4,4,4,5,6,7,8,9]
    BOOST_ASSERT( v.size() == 3 + 10 + 5 );
    
    v = list_of(1).repeat(5,2)(3);
    // v = [1,2,2,2,2,2,3]
    BOOST_ASSERT( v.size() == 1 + 5 + 1 );
    
    push_back( v )(1).repeat(1,2)(3);
    // v = old v + [1,2,3]
    BOOST_ASSERT( v.size() == 10 );
}
As we can see, then the first argument to repeat() is the number of times to repeat the second argument.

A more general list can be constructed with repeat_fun():

#include <boost/assign/std/vector.hpp>
#include <boost/assert.hpp>
#include <cstdlib> // for 'rand()'              

using namespace std;
using namespace boost::assign;
 
template< class T >
struct next    
{
    T seed;
    next( T seed ) : seed(seed) 
    { }
    
    T operator()() 
    {
        return seed++;
    }
};
     
{
    vector<int> v;
    v += 1,2,repeat_fun(4,&rand),4;
    // v = [1,2,?,?,?,?,4] 
    BOOST_ASSERT( v.size() == 7 );
    
    push_back( v ).repeat_fun(4,next<int>(0))(4).repeat_fun(4,next<int>(5));
    // v = old v + [0,1,2,3,4,5,6,7,8] 
    BOOST_ASSERT( v.size() == 16 );
}        
The only requirement of the second argument to repeat_fun() is that it is a nullary function.

If you just need to insert an iterator-range somewhere in the list, the member function range() provides just what you want. It is based on Boost.Range, so you can pass all the ranges supported by that library. For example

#include <boost/assign/list_inserter.hpp> // for 'push_back()'
#include <boost/assign/list_of.hpp>       // for 'list_of()' and 'ref_list_of()'
#include <boost/assert.hpp>

using namespace std;
using namespace boost::assign;
 
{
    vector<int> v, v2;
    v  = list_of(1)(2)(3);
    v2 = list_of(0).range(v).range(v.begin(),v.end())(4);
    // v2 = [0,1,2,3,1,2,3,4]
    BOOST_ASSERT( v2.size() == 8u );

    push_back( v ).range(v2)(5);
    // v = [1,2,3,0,1,2,3,1,2,3,4,5]
    BOOST_ASSERT( v.size() == 12u ); 

    //
    // create a list of references, some coming from a container, others from the stack 
    //
    int x = 0;
    int y = 1;
    BOOST_ASSERT( ref_list_of<10>(x).range(v2)(y).size() == 10u );
}
As you can see, one can also pass two iterators if that is more appropriate. The last example also introduces list of references. More about that below.

Functions ref_list_of() and cref_list_of()

When you need to create an anonymous range of values and speed is essential, these two functions provide what you want.
#include <boost/assign/list_of.hpp>
#include <algorithm>

//
// Define Range algorithm
//
template< class Range >
typename Range::const_iterator max_element( const Range& r )
{
    return std::max_element( r.begin(), r.end() );
}

using namespace boost::assign;

{
    int a=1,b=5,c=3,d=4,e=2,f=9,g=0,h=7;
    int& max = *max_element( ref_list_of<8>(a)(b)(c)(d)(e)(f)(g)(h) );
    BOOST_CHECK_EQUAL( max, f );
    max = 8;
    BOOST_CHECK_EQUAL( f, 8 );
    const int& const_max = *max_element(cref_list_of<8>(a)(b)(c)(d)(e)(f)(g)(h) );
    BOOST_CHECK_EQUAL( max, const_max );
}
    
You can only use lvalues with ref_list_of() while cref_list_of() accepts rvalues too. Do not worry about not specifying exactly the right size; the extra space used is minimal and there is no runtime overhead associated with it. You may also use these functions instead of list_of() if speed is essential.

A "complicated" example

As a last example, let us assume that we need to keep track of the result of soccer matches. A team will get one point if it wins and zero otherwise. If there has been played three games in each group, the code might look like this:

#include <boost/assign/list_of.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/assert.hpp>
#include <string>
#include <vector>

using namespace std;
using namespace boost::assign;
 
{
    typedef vector<int>                   score_type;
    typedef map<string,score_type>        team_score_map;
    typedef pair<string,score_type>       score_pair;

    team_score_map group1, group2;
    
    //
    // method 1: using 'insert()'
    //
    insert( group1 )( "Denmark", list_of(1)(1) )
                    ( "Germany", list_of(0)(0) )
                    ( "England", list_of(0)(1) );
    BOOST_ASSERT( group1.size() == 3 );
    BOOST_ASSERT( group1[ "Denmark" ][1] == 1 );
    BOOST_ASSERT( group1[ "Germany" ][0] == 0 );
    
    //
    // method 2: using 'list_of()'
    //
    group2 = list_of< score_pair >
                        ( "Norway",  list_of(1)(0) )
                        ( "USA",     list_of(0)(0) )
                        ( "Andorra", list_of(1)(1) );
    BOOST_ASSERT( group2.size() == 3 );
    BOOST_ASSERT( group2[ "Norway" ][0] == 1 );
    BOOST_ASSERT( group2[ "USA" ][0] == 0 );
}
    
In the first example, notice how the result of list_of() can be converted automatically to a vector<int> because insert() knows it expects a vector<int>. In the second example we can see that list_of() is somewhat less intelligent since here it needs to be told explicitly what arguments to expect. (In the future it might be possible to introduce a more intelligent conversion layer in list_of().)

Functions ptr_push_back(), ptr_push_front(), ptr_insert() and ptr_map_insert()

For use with Boost.Pointer Container a few special exception-safe functions are provided. Using these function you do not need to call new manually:
#include <boost/assign/ptr_list_inserter.hpp> // for 'ptr_push_back()', 'ptr_insert()' and 'ptr_push_front()'
#include <boost/assign/ptr_map_inserter.hpp>  // for 'ptr_map_insert()'
#include <boost/ptr_container/ptr_deque.hpp>
#include <boost/ptr_container/ptr_set.hpp>
#include <boost/ptr_container/ptr_map.hpp>

//
// Example class
//
struct Foo
{
    int i;
    
    Foo() : i(0)
    { }
    Foo( int i ) : i(i)
    { }
    Foo( int i, int ) : i(i)
    { }
    Foo( const char*, int i, int ) : i(i)
    { }

    virtual ~Foo()
    {}
};

struct Bar : Foo
{
    Bar()
    { }
    
    Bar( int i ) : Foo( 42 )
    { }
};

//
// Required by ptr_set<Foo>
//
inline bool operator<( Foo l, Foo r )
{
    return l.i < r.i;
}

 
using namespace boost;
using namespace boost::assign;

int main()
{
    ptr_deque<Foo> deq;
    ptr_push_back( deq )()();
    BOOST_ASSERT( deq.size() == 2u );
    ptr_push_back<Bar>( deq )()(); // insert 'Bar' objects
    BOOST_ASSERT( deq.size() == 4u );
    ptr_push_front( deq )( 3 )( 42, 42 )( "foo", 42, 42 );
    BOOST_ASSERT( deq.size() == 7u );

    ptr_set<Foo> a_set;
    ptr_insert( a_set )()( 1 )( 2, 2 )( "foo", 3, 3 );
    BOOST_ASSERT( a_set.size() == 4u );
    ptr_insert( a_set )()()()();
    BOOST_ASSERT( a_set.size() == 4u ); // duplicates not inserted
    ptr_insert<Bar>( a_set )( 42 ); // insert a 'Bar' object 
    BOOST_ASSERT( a_set.size() == 5u );

    ptr_map<int,Foo> a_map;
    ptr_map_insert( a_map )( 1 )( 2, 2 )( 3, 3, 3 )( 4, "foo", 4, 4 );
    ptr_map_insert<Bar>( a_map )( 42, 42 ); // insert a  'Bar' object
}
    
Notice how you may provide a template argument to these functions. This argument determines the type to allocate with new. You have to specify this argument when the container is based on an abstract type (because one cannot create objects of such a type).

For ptr_map_insert() the first argument arg1 in an argument tuple (arg1,arg2,...,argN) is used to construct a key; this means that the first argument need only be convertible to the key_type of the container. The rest of the arguments are used to construct the mapped object.

Function ptr_list_of()

Just like you can use list_of() to initialize containers, you can use ptr_list_of() to initialize a pointer container. Here is a small example:
#include <boost/assign/ptr_list_of.hpp>
#include <boost/ptr_container/ptr_deque.hpp>

using namespace boost;
using namespace boost::assign;

{
    ptr_deque<Foo> deq;
    deq = ptr_list_of<Foo>( 42 )()()( 3, 3 )( "foo", 2, 1 );
    BOOST_CHECK( deq.size() == 5 );
}    
    
Notice that a trailing .to_container(deq) may be added to help many poor compilers to figure out the conversion (a few get it right). Notice also that pointer maps are not supported.

That is all; now you are ready to use this library.


Reference

It is worth noticing the way the library is implemented. A free-standing function (eg. push_back() or operator+=()) returns a proxy object which is responsible for the insertion or the assignment. The proxy object does the insertion or assignment by overloading operator,() and operator()() and by calling the "insert" function from within those operators. The "insert" function is typically stored in the proxy object by using boost::function.

Often overloading of operator,() is discouraged because it can lead to surprising results, but the approach taken in this library is safe since the user never deals with objects that have overloaded operator,() directly. However, you should be aware of this:

The expressions in a comma-separated list no longer follow the rules of the built-in comma-operator. This means that the order of evaluation of expressions in a comma-separated list is undefined like when one specifies a list of function arguments.

Most of the code in this document use int in the examples, but of course it works for arbitrary types as long as they are Copy Constructible. The inserted data need not be constant data, but can be variables or data returned from functions; the only requirement is that the type of the data is convertible to the type stored in the container.

All forwarding is done by passing objects by const reference. Originally arguments were passed by value (and still is in tuple_list_of()). One thing to remember is that references can be passed by using boost::ref.

Everything is put in namespace boost::assign.

More details can be found below:

Headers

An overview of the headers in this library is given below. Please notice <boost/assign/list_inserter.hpp> is included for each header that defines operator+=().

Header Includes
<boost/assign.hpp> everything except support for pointer containers
<boost/assign/list_of.hpp> list_of(), map_list_of(), tuple_list_of(), ref_list_of() and cref_list_of()
<boost/assign/std.hpp> operator+=() for all standard containers (see below)
<boost/assign/std/deque.hpp> operator+=() for std::deque, <deque>
<boost/assign/std/list.hpp> operator+=() for std::list, <list>
<boost/assign/std/map.hpp> operator+=() for std::map and std::multimap , <map>
<boost/assign/std/queue.hpp> operator+=() for std::queue and std::priority_queue, <queue>
<boost/assign/std/set.hpp> operator+=() for std::set and std::multiset, <set>
<boost/assign/std/slist.hpp> operator+=() for std::slist if the class is available , <slist>
<boost/assign/std/stack.hpp> operator+=() for std::stack, <stack>
<boost/assign/std/vector.hpp> operator+=() for std::vector, <vector>
<boost/assign/assignment_exception.hpp> Class assignment_exception which might be thrown by the proxy returned by list_of()
<boost/assign/list_inserter.hpp> Functions make_list_inserter(), push_back(), push_front(),insert(), push() and class list_inserter which is the back-bone of this entire library.
<boost/assign/ptr_list_inserter.hpp> Functions ptr_push_back(), ptr_push_front() and ptr_insert()
<boost/assign/ptr_map_inserter.hpp> Functions ptr_map_insert()
<boost/assign/ptr_list_of.hpp> Function ptr_list_of()

Standard containers

In the following three dots (...) will mean implementation defined. operator+=() returns a proxy that forwards calls to either push_back(),insert(), or push() depending on which operation the container supports.

Synopsis

namespace boost
{
namespace assign
{
    template< class V, class A, class V2 >
    list_inserter< ... >    operator+=( std::deque<V,A>& c, V2 v );
    
    template< class V, class A, class V2 >
    list_inserter< ... >    operator+=( std::list<V,A>& c, V2 v );
    
    template< class K, class V, class C, class A, class P >
    list_inserter< ... >    operator+=( std::map<K,V,C,A>& m, const P& p );
    
    template< class K, class V, class C, class A, class P >
    list_inserter< ... >    operator+=( std::multimap<K,V,C,A>& m, const P& p );
    
    template< class V, class C, class V2 >
    list_inserter< ... >    operator+=( std::queue<V,C>& c, V2 v );
    
    template< class V, class C, class V2 >
    list_inserter< ... >    operator+=( std::priority_queue<V,C>& c, V2 v );
    
    template< class K, class C, class A, class K2 >
    list_inserter< ... > operator+=( std::set<K,C,A>& c, K2 k );
    
    template< class K, class C, class A, class K2 >
    list_inserter< ... > operator+=( std::multiset<K,C,A>& c, K2 k );
    
    #ifdef BOOST_HAS_SLIST
              
    template< class V, class A, class V2 >
    list_inserter< ... >    operator+=( std::slist<V,A>& c, V2 v );
    
    #endif
    
    template< class V, class C, class V2 >
    list_inserter< ... >    operator+=( std::stack<V,C>& c, V2 v );
    
    template< class V, class A, class V2 >
    list_inserter< ... >    operator+=( std::vector<V,A>& c, V2 v );    

} // namespace 'assign'
} // namespace 'boost'  
Note that the extra template argument V2 etc. is necessary to allow for types convertible to V.

Functions list_of() and map_list_of()

These two functions are used to construct anonymous list which can be converted to any standard container and boost::array<T,sz>. The object returned by the two functions is guaranteed to have the interface described below.

Synopsis
namespace boost  
{
namespace assign
{
    template< class T >
    class Implementation-defined
    {
    public:
        const_iterator  begin() const;
        const_iterator  end() const;
        
        template< class U >
        Implementation-defined& operator,( U u );
        
        // inserts default-constructed object
        Implementation-defined& operator()();  

        template< class U >
        Implementation-defined& operator()( U u );
        
        template< class U, class U2 >
        Implementation-defined& operator()( U u, U2 u2 );

        //
        // and similarly up to 5 arguments
        //
        
        //
        // Convert to a 'Container'. 'Container' must have a constructor 
        // which takes two iterators.  
        //
        template< class Container >
        operator Container() const; 

        //
        // Convert to a container adapter like 'std::stack<>'.
        //
        Convertible-to-adapter to_adapter() const;
        
        //
        //
        // Convert to eg. 'boost::array<T,std::size_t>'. If the  
        // assigned variable is too small, 
        // a assignment_exception is thrown.
        // If the assigned variable it is too big, the rest of the 
        // values are  default-constructed.
        //
        template< template <class,std::size_t> class Array, class U, std::size_t sz > 
        operator Array<U,sz>() const;
    };
    
    //
    // Comparison operators. 'op' can be <,>,<=,>=,==,!=
    //
    template< class Range >
    bool op( const Implementation-defined&, const Range& );
    template< class Range >
    bool op( const Range&, const Implementation-defined& );
    
    template< class T >
    Implementation-defined   list_of();

    template< class T >
    Implementation-defined   list_of( T t );
    
    template< class T, class U, class U2 >
    Implementation-defined   list_of( U u, U2 u2 );
    
    template< class T, class U, class U2, class U3 >
    Implementation-defined   list_of( U u, U2 u2, U3 u3 );

    template< class T, class U, class U2, class U3, class U4 >
    Implementation-defined   list_of( U u, U2 u2, U3 u3, U4 u4 );
  
    template< class T, class U, class U2, class U3, class U4, class U5 >
    Implementation-defined   list_of( U u, U2 u2, U3 u3, U4 u4, U5 u5 );

    template< class Key, class T >
    Implementation-defined   map_list_of( Key k, T t )
    {
        return list_of< std::pair<Key,T> >()( k, t );
    }
} // namespace 'assign'
} // namespace 'boost'  

Functions repeat(), repeat_fun() and range()

These first two function exist both as free-standing functions and as member functions of the object returned by list_of() and of list_inserter. The free-standing versions are used to create a hook for operator,() so we can call the functions in the middle of a comma-list. The member functions are used when we need to call the functions in the middle of a parenthesis-list. In both cases we have that

The function range() only exists as a member function. The following two overloads are provided:

template< class SinglePassIterator >
Implementation-defined range( SinglePassIterator first, SinglePassIterator last );

template< class SinglePassRange >
Implementation-defined range( const SinglePassRange& rng );

Class list_inserter

This class is responsible for inserting elements into containers and it is the key to extending the library to support your favourite class.

Synopsis

namespace boost
{
namespace assign
{
    template< Function, Argument = void > 
    class list_inserter
    {
        Function fun;
        
    public:
        explicit list_inserter( Function fun );
        
        // conversion constructor
        template< class Function2, class Arg >
        list_inserter( const list_inserter<Function2,Arg>& );
        
    public:
        template< class U >
        list_inserter& operator,( U u );
        
        template< class U >
        list_inserter& operator=( U u );
        
        // calls 'fun()' with default-constructed object
        list_inserter& operator()();
        
        template< class U >
        list_inserter& operator()( U u );
        
        template< class U, class U2 >
        list_inserter& operator()( U u, U2 u2 )
        {
           //
           // if 'Argument' is 'void'
           //     fun( u, u2 );
           // else
           //     fun( Argument( u, u2 ) );
           //
           return *this;
        }

        //
        // similarly up to 5 arguments
        //
    };
    
    template< class C >
    list_inserter< ... > push_back( C& );
      
    template< class C >
    list_inserter< ... > push_front( C& );

    template< class C >
    list_inserter< ... > insert( C& );

    template< class C >
    list_inserter< ... > push( C& );
      
} // namespace 'assign'
} // namespace 'boost'

Notice how the arguments to operator,() and operator()() are passed differently to fun depending of the type of Argument. So if we only pass one template argument to list_inserter, we can forward "arbitrary" argument lists of functions. If we pass two template arguments to list_inserter we can construct types with "arbitrary" constructors.

And because a reference to list_inserter is returned, we can chain argument list together in a very space-efficient manner.

Function make_list_inserter()

A simple "constructor" function for list_inserter. A typical use of this function is to call it with the result of boost::bind() which in general returns some unreadable and weird class template.

Synopsis
namespace boost 
{
namespace assign
{  
    template< class Function >
    list_inserter<Function>  make_list_inserter( Function fun )
    {
        return list_inserter<Function>( fun );
    } 
}
}    

Customizing argument list sizes

This library uses the boost Preprocessor Library to implement overloaded versions of operator()() and list_of(). By default you can call these functions with five arguments, but you can also customize this number by defining a macros before including a header from this library:

#define BOOST_ASSIGN_MAX_PARAMS 10
#include <boost/assign.hpp>


Exceptions and exception-safety

The exception guarantees by the library is the same as guarantee as the guarantee of the function that is forwarded to. For standard containers this means that the strong guarantee is given for a single insertions and that the basic guarantee is given for many insertions (provided that the object being copied gives the basic guarantee).

The functions may throw standard exceptions like std::bad_alloc. Note however that, unfortunately, the standard does not guarantee allocation-failures in standard containers to be reported by std::bad_alloc or exceptions derived from std::exception.

Class assignment_exception

The exception is thrown by the conversion operator in the proxy object returned from list_of().

namespace boost 
{
namespace assign
{
    class assignment_exception : public std::exception
    {
    public:
        explicit assignment_exception( const char* what ); 
        virtual const char* what() const throw();
    };
}   
}  

Extending the library

It is very simple to make the library work with new classes. This code shows how to use operator+=() with a container:

template< class V, class A, class V2 >
inline list_inserter< assign_detail::call_push_back< std::vector<V,A> >, V > 
operator+=( std::vector<V,A>& c, V2 v )
{
    return make_list_inserter( assign_detail::call_push_back< std::vector<V,A> >( c ) )( v );
}
where call_push_back is defined as
template< class C >
class call_push_back
{
    C& c_;
public:

    call_push_back( C& c ) : c_( c )
    { }
    
    template< class T >
    void operator()( T r ) 
    {
        c_.push_back( r );
    }
};
Note that we pass a second template argument to list_inserter so argument lists will be used to construct a V object. Otherwise we could end up trying to call push_back() with n arguments instead of one.

An alternative way would be to use boost::function and boost::bind() in combination. However, in this case one must remember that it is illegal to take the address of a function in the standard library.

Calling a function with more that one argument can be very useful too. This small example shows how we take advantage of this functionality:

//  
// A class representing emails
//
class email
{
public:
    enum address_option
    {
        check_addr_book,
        dont_check_addr_book
    };
    
private:

    typedef std::map< std::string,address_option >  address_map;
    
    //
    // Store list of persons that must be cc'ed
    //
    mutable address_map cc_list;
        
    //
    // This extra function-object will take care of the 
    // insertion for us. It stores a reference to a 
    // map and 'operator()()' does the work. 
    //
    struct add_to_map
    {
        address_map& m;
    
        add_to_map( address_map& m ) : m(m)        
        {}
    
        void operator()( const std::string& name, address_option ao )
        {
            m[ name ] = ao; 
        }
    };

public:
    
    //
    // This function constructs the appropriate 'list_inserter'.
    // Again we could have use 'boost::function', but it is
    // trivial to use a function object.
    //
    // Notice that we do not specify an extra template
    // parameter to 'list_inserter'; this means we forward
    // all parameters directly to the function without 
    // calling any constructor.
    //
    list_inserter< add_to_map >
    add_cc( std::string name, address_option ao )
    {
        //
        // Notice how we pass the arguments 'name' and 'ao' to
        // the 'list_inserter'.
        //
        return make_list_inserter( add_to_map( cc_list ) )( name, ao );
    }
};

//
// Now we can use the class like this:
//
email e;
e.add_cc( "Mr. Foo", email::dont_check_addr_book )
        ( "Mr. Bar", email::check_addr_book )
        ( "Mrs. FooBar", email::check_addr_book );  
The full example can be seen in email_example.cpp


Examples

Additional examples can be found in the test files:


Supported libraries

Here is a list libraries has been tested with Boost.Assign:
  1. boost::array
  2. boost::multi_index_container
  3. Boost.Pointer Container


Portability

Library has been successfully compiled and tested with MVC++ 7.1, GCC 3.2 (under Cygwin) Comeau 4.3.3

There are known limitation on platforms not supporting templated conversion operators. The solution is to call certain member functions on the object returned by list_of():

{
    using namespace std;
    using namespace boost;
    using namespace boost::assign;
    
    vector<int>         v = list_of(1)(2)(3)(4).to_container( v );
    set<int>            s = list_of(1)(2)(3)(4).to_container( s );  
    map<int,int>        m = map_list_of(1,2)(2,3).to_container( m );
    stack<int>         st = list_of(1)(2)(3)(4).to_adapter( st );
    queue<int>          q = list_of(1)(2)(3)(4).to_adapter( q ); 
    array<int,4>        a = list_of(1)(2)(3)(4).to_array( a );
}     

Notice how one must supply the functions with an argument so the right return type can be deduced.

Some standard libraries are also broken. One problem is that insert() might not work:

map<int,int> next; 
insert( next )(1,2)(2,3); // compile-time error 
The solution is to use map_list_of() instead:
map<int,int> next = map_list_of(1,2)(2,3);


History and Acknowledgment

The idea for an assignment/initialization library is not new. The functionality of this library resembles Leor Zolman's STL Container Initialization Library a great deal, but it does not rely on string parsing to achieve its goals.

The library is non-intrusive and puts only a minimum of requirements on its supported classes. Overloading operator comma is sometimes viewed as a bad practice [1]. However, it has been done with success in eg. the Generative Matrix Computation Library and Blitz to initialize matrices (see [2]) and [3]). The Initialization Library overloads the comma operator in a safe manner by letting free standing functions return an object that is responsible for the initialization. Therefore it takes explicit action from the programmer to begin using the overloaded operator,().

There has recently been some discussion about enhancing the language to support better initialization (see [4]).

Special thanks goes to


References

  1. Scott. Meyers, "More Effective C++", Item 7, Addison Wesley, 1996
  2. K. Czarnecki and U.W. Eisenecker, "Generative programming", Addison-Wesley, 2000
  3. http://www.oonumerics.org/blitz/
  4. Gabriel Dos Reis and Bjarne Stroustrup, "Generalized Initializer Lists", 2003


(C) Copyright Thorsten Ottosen 2003-2006