Boost::bind is “able to bind any argument to a specific value or route input arguments into arbitrary positions.” It’s a means of converting a function into an object that can be copied around and called at a later point, deferred callbacks for example.
An example of its power becomes evident when combined with its overloads for operator==
so that you can combine with find_if
(or copy_if
, remove_if
, etc) to call any member function of a class in a container. See here for setting up Boost in Visual Studio environments.
#include <vector> #include <sstream> #include <algorithm> #include "boost/bind.hpp" class Record { public: Record() {} Record( std::string nm, int age_val ) { name = nm; age = age_val; } std::string GetName() const { return name; } unsigned int GetAge() const { return age; } private: std::string name; unsigned int age; }; struct DataRec { std::string name; int age; }; typedef DataRec data; void main() { // Set up some data data dat[] = { { "Andrew", 10 }, { "Mark", 20 }, { "John", 30 }, { "Mike", 40 } }; // Add some records std::vector< Record* > rec; int Recs = sizeof( dat ) / sizeof( dat[ 0 ] ); for ( int count = 0; count < Recs; count++ ) { rec.push_back( new Record( dat[ count ].name, dat[ count ].age ) ); } // Find the record matching the given string std::vector< Record* >::iterator it; it = std::find_if( rec.begin(), rec.end(), boost::bind( &Record::GetName, _1 ) == "Mike"); int age = (*it)->GetAge(); // and don't forget to delete of course... }