Boost logo

Boost :

From: John Torjo (john.lists_at_[hidden])
Date: 2004-03-19 02:54:13


Dear boosters,

Right now, you need to type pretty much if you want to bind, lets say to
the key or value from a collection.
Example:
typedef std::map<int,std::string> map;
bind(&map::value_type::first,_1); // bind to key
bind(&map::value_type::second,_1); // bind to value

I've made two utility classes, in order to lessen the amount of typing.
Also, an example is provided.

#include <boost/bind.hpp>
#include <map>
#include <string>
#include <iostream>

namespace boost { namespace coll {
    template< class coll_type> struct key {
        typedef typename coll_type::value_type pair;
        typedef typename pair::first_type result_type;
        result_type operator()( const pair & p) {
            return p.first;
        }
    };

    template< class coll_type> struct val {
        typedef typename coll_type::value_type pair;
        typedef typename pair::second_type result_type;
        result_type operator()( const pair & p) {
            return p.second;
        }
    };
}}

void print_int( int i) { std::cout << i << std::endl; }
void print_str( const std::string & s) { std::cout << s << std::endl; }

int main(int argc, char* argv[])
{
    typedef std::map<int,std::string> map;
    map m;
    m[1] = "one";
    m[2] = "two";
    m[3] = "three";

    using namespace boost;
    using namespace boost::coll;
    // using key & val utility classes
    std::for_each( m.begin(), m.end(), bind( print_int,
bind(key<map>(),_1)) ); // bind to key
    std::for_each( m.begin(), m.end(), bind( print_str,
bind(val<map>(),_1)) ); // bind to val

    // how you can bind to key or value from a collection, now
    std::for_each( m.begin(), m.end(), bind( print_int,
bind(&map::value_type::first,_1)) );
    std::for_each( m.begin(), m.end(), bind( print_str,
bind(&map::value_type::second,_1)) );
    return 0;
}

Best,
John


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk