Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C++
Article

An Introduction to Boost

Rate me:
Please Sign up or sign in to vote.
4.70/5 (36 votes)
6 Jul 20036 min read 297.3K   107   32
An overview of the Boost library

Contents

  1. Introduction
  2. Installation
  3. Why Boost?
  4. What Does Boost Provide?
  5. What Else?
  6. References
  7. Version History

Introduction

Boost is a free library which is aimed at providing quality software components to developers, whilst using the styles of the Standard Template Library. Some of the components within the library may be put forward as future extensions to the Standard Library.

The Boost main page
The Boost libraries index
CUJ Descriptions of the boost components

The Boost homepage contains extensive documentation on all of the individual components. This article is intended to be an overview of why you should consider using Boost, and the Boost components in preference to other libraries, and to provide a location on CodeProject which can offer links to related documentation.

Installation

Boost installation is simple because most of the components within the library reside in their own header files, which should not require modification. The BoostJam build tool is available for the components which do require compilation.

You can download the source zip from SourceForge.

Unzip the entire archive into a directory of your choosing. To start using the components add the Boost directory which includes version numbers to your include path. For the current version of Boost, boost_1_30_0.

Most of the components come with test suites and examples of use.

Why Boost?

  • Boost is namespace aware. All components within the library are packaged in the "boost" namespace, or a sub-namespace thereof.
  • Regular updates. Boost is a library which is growing all the time, the home page and the Boost Announcements Lists show some of the changes in the last few releases.
  • Developer support. Questions related to the components can be directed to the Boost users mailing group, or found on the Boost Mail Archives or on one of the specific lists for a particular component.
  • Boost supports a variety of compilers, operating systems and standard libraries. It provides workarounds for the broken features of many compilers, perhaps the most significant being the workarounds for problems with templates, including partial template specialisation and member template friends.
  • Regression testing. Each update to Boost is heavily regression tested, and the status of the library for all compilers is freely available.
  • Many of the people involved with the development of the C++ standard are involved with Boost.
  • Simple to install and upgrade. In most cases, installation and upgrading only requires the addition or change of one include path.
  • Easy to configure. Compilation options can be specified by changing directives in one or two header files.

What Does Boost Provide?

What follows is a minimal listing of components. There are about 50 major sub-components in Boost at the moment. The following components were those that I felt logically progressed from the components in the STL, were easy to integrate, or were especially significant to most programmers.

Smart Pointers

Smart pointers are tools that prevent resource leaks (especially in the presence of exceptions), promote the concept of 'Initialisation is Resource Acquisition'. They emulate, to a certain extent, garbage collection like behaviour.

Most of the limitation of std::auto_ptr are relatively well known:
  • std::auto_ptr's cannot be stored within a standard containers.
  • std::auto_ptr's cannot (easily) be used to implement the pImpl (pointer-to-implementation) idiom.
  • std::auto_ptr does not work with arrays.
The 5 types of Boost smart pointers overcome these flaws and provide many extra features.
  • Custom delete functions can be supplied.
  • Detection of incomplete template types.
Boost smart pointer index
Comparison of Boost and Loki Smart Pointers The New C++: Smart(er) Pointers - Herb Sutter
Introduction to uses of the Boost smart pointers Conversations: Getting to the Point - Herb Sutter and Jim Hyslop

Composers

Functors and binders have become a common part of using the STL, but using most standard library implementations it can still be difficult to combine multiple functions. Composers allow functors to be combined in several ways, minimising the amount of times that users have to write their own loops.

Boost::compose index
The C++ Standard Library - A Tutorial and Reference (Nicolai M. Josuttis)

Any

A component which provides a type safe way to move any type of component, without having to rely upon void pointers or unions. The design principles for this component is at least as significant as the component itself (derivation of a template class from a non template base class). Something similar to boost::any appears in Alexandrescu’s Modern C++ Design in the guise of Functors and Functor Implementations.

boost::any main page
boost::any Theory
Introduction to uses of Boost Any Conversations: I'd Hold Anything for You - Herb Sutter

Bind and Function

Bind and Function are specified as two separate components, but they are extensions (any number of arguments) of binders and functors concept which are currently in place in the Standard Library.

boost::function main page
boost::bind main page

The Lambda Library

The lambda library provides a shortcut for producing binders, functors and composers using expression templates. My personal opinion on the library is that developers would need some practice to recognise it’s use. Libraries like the Lambda library are probably the way of the future for C++, but at the moment, I think I’m prepared to have slower uglier code that I know the next guy can understand.

The Boost Lambda Library Index
Further information on the basics of expression templates was published in the March issue of the C/C++ users journal (C++ Expression Templates – Angelika Langer and Klaus Kreft)

The Boost Graph Library (The BGL)

The BGL is a huge library, with a large amount of support material and good sample programs. “The Boost Graph Library, The: User Guide and Reference Manual” has been published by Addison-Wesley in the C++ In Depth Series (The same fantastic series that includes 'Exceptional C++', 'More Exceptional C++' and 'Modern C++ Design'), which I believe is testament to the quality of the library.

Boost Graph Library Table of Contents
The Boost Graph Library, The: User Guide and Reference Manual Book Review

Thread

Developed by Code Project regular William E. Kempf, the threads library makes it seem almost as easy to do threads in C++ as it is in Java. It requires linking to an additional library, built with BoostJam.

boost::threads index
William E. Kempf on boost::thread

Spirit parser generator framework

Jonathan de Halleux has written an excellent introduction to the Spirit Parser Generator Framework with comprehensive links to relevant material

What Else?

  • Regular Expressions
  • Traits
  • File System (Directory Iteration)
  • Iterator Adaptors
  • Maths and Matrices
  • A Template metaprogramming framework
  • Tuples
  • Python

References

Many of the references in this article come from the C / C++ Users journal website, which is an excellent resource for up to date information on uses, and techniques for using STL and Boost.

Additional information about Boost can be found at Boost Consulting

This article was inspired by an item in the 'Article Requests and Ideas' Forum by John M. Drescher

Version history

30. 6. 2003 Initial Posting

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
Andrew is a PhD student at Swinburne University in Melbourne Australia, investigating the control systems of UUV's - Unmanned Underwater Vehicles. He graduated from Swinburne with a Bachelor of Engineering (Robotics and Mechatronics) and a Bachelor of Science(Computer Science & Software Engineering)

His practical experience includes a year developing an industrial computer vision system from scratch, and working as the software architect for the 2004 Swinburne Robocup team (f180 league).

Comments and Discussions

 
GeneralMy vote of 1 Pin
Virendra Kulkarni16-Sep-09 0:24
Virendra Kulkarni16-Sep-09 0:24 
GeneralProblem while using string.hpp Pin
tonyaim8327-Aug-07 19:45
tonyaim8327-Aug-07 19:45 
GeneralRe: Problem while using string.hpp Pin
foxconn8-Apr-08 4:08
foxconn8-Apr-08 4:08 
QuestionHow to use this library? Pin
bosfan12-Oct-06 3:17
bosfan12-Oct-06 3:17 
Questionn-ary tree? Pin
Anthony_Yio13-Apr-04 22:14
Anthony_Yio13-Apr-04 22:14 
AnswerRe: n-ary tree? Pin
Andrew Walker13-Apr-04 22:56
Andrew Walker13-Apr-04 22:56 
GeneralRe: n-ary tree? Pin
Anthony_Yio14-Apr-04 1:43
Anthony_Yio14-Apr-04 1:43 
GeneralRe: n-ary tree? Pin
unjedai22-May-07 16:50
unjedai22-May-07 16:50 
GeneralIntroductory Boost Presentation Pin
MattyT18-Nov-03 12:41
MattyT18-Nov-03 12:41 
GeneralRe: Introductory Boost Presentation Pin
theCPkid16-Apr-09 21:58
theCPkid16-Apr-09 21:58 
GeneralBoost Submitted libraries Pin
Jonathan de Halleux15-Jul-03 0:34
Jonathan de Halleux15-Jul-03 0:34 
GeneralRe: Boost Submitted libraries Pin
Andrew Walker15-Jul-03 2:01
Andrew Walker15-Jul-03 2:01 
GeneraluBLAS Pin
Jonathan de Halleux16-Jul-03 4:01
Jonathan de Halleux16-Jul-03 4:01 
GeneralAt last Pin
Jonathan de Halleux15-Jul-03 0:30
Jonathan de Halleux15-Jul-03 0:30 
Generalauto_ptrs Pin
Adi Shavit7-Jul-03 23:05
Adi Shavit7-Jul-03 23:05 
GeneralRe: auto_ptrs Pin
Mårten R9-Jul-03 4:34
Mårten R9-Jul-03 4:34 
GeneralRe: auto_ptrs Pin
Adi Shavit9-Jul-03 10:15
Adi Shavit9-Jul-03 10:15 
GeneralThank You Pin
John M. Drescher7-Jul-03 11:31
John M. Drescher7-Jul-03 11:31 
GeneralRe: Thank You Pin
Andrew Walker7-Jul-03 15:03
Andrew Walker7-Jul-03 15:03 
GeneralRe: Thank You Pin
John M. Drescher8-Jul-03 9:20
John M. Drescher8-Jul-03 9:20 
GeneralRe: Thank You Pin
Andrew Walker8-Jul-03 16:04
Andrew Walker8-Jul-03 16:04 
GeneralRe: Thank You Pin
John M. Drescher8-Jul-03 16:10
John M. Drescher8-Jul-03 16:10 
GeneralRe: Thank You Pin
Andrew Walker8-Jul-03 16:25
Andrew Walker8-Jul-03 16:25 
GeneralRe: Thank You Pin
John M. Drescher25-Jul-03 7:02
John M. Drescher25-Jul-03 7:02 
GeneralBoost Function (long) Pin
Andrew Walker25-Jul-03 18:47
Andrew Walker25-Jul-03 18:47 
John M. Drescher wrote:
Recently a article http://www.codeproject.com/cpp/CallbackDemo.asp

Just a couple of comments on that particular article:
- The way the sample app is written makes it relatively hard to see what callbacks are doing
- Big chunks of the code aren't type safe (void pointers) - big mental alarm bells start ringing in my head, getting all the louder when I see C-style casts.
- Some of the functions should really be using standard library elements, without even considering boost.

In the cases where you're writing the code, it's generally easiest to specify that anything with function call semantics is acceptable. The simplest way to do that is to templatize all of the functions. STL does this, that's why all the STL algorithms are templatized. Function objects in the standard are meant to be light-weight, so the types shouldn't really be significant. The consequence of that is that it's hard to exchange global functions for member function pointers.

The following code, which is a rewrite of the mentioned article's sample code uses boost::bind. If the callback does not support a conversion to a string type, the build will fail.

The basic idea to remember is that a callback (for a member function) needs to have two things: first an object pointer (or reference) and second the member function pointer. Binding like this allows you to attach the object to the member function pointer, in this case most if not all of this should be possible without using boost, by just using standard library elements (the second part of my response isn't). What makes boost bind/function/mem_fn outstanding in this area is that you can have any number of arguments.
#include <iostream>
#include <sstream>
#include <boost/bind.hpp>

using namespace std;

template<class T>
void globalCallback(T callback)
{
    ostringstream oss;
    oss << "From a global callback" << endl;
    callback(oss.str());
}

class Add
{
public:
    // generated ctor & dtor ok.

    template<class T>
    bool addNumbers(int num1, int num2, T callback)
    {
        ostringstream oss;
        oss << "Adding    " << num1 << " + " << num2 << " = " << (num1+num2) << endl;
        callback(oss.str());
        return true;
    }
};

class Multiply
{
public:
    // generated ctor & dtor ok.

    template<class T>
    bool multiplyNumbers(int num1, int num2, T callback)
    {
        ostringstream oss;
        oss << "Adding    " << num1 << " * " << num2 << " = " << (num1*num2) << endl;
        callback(oss.str());
        return true;
    }
};

class Test  
{
public:

    // generated ctor & dtor ok.

    void testStart()
    {
        cout << "Start" << endl;

        Add add;   // local instances
        Multiply multi;

        // -------------- Demo 1 : normal callback ----------------------
        cout << "\n> Setting CallbackOutputStars !\n";
        add.addNumbers       (120, 30, boost::bind(&Test::callbackOutputStars,this,_1));
	    multi.multiplyNumbers(3,   22, boost::bind(&Test::callbackOutputStars,this,_1));

        // -------------- Demo 2 : changing the callback ----------------
        cout << "\n> Setting CallbackOutputDollar !\n";
        add.addNumbers       (33, 66, boost::bind(&Test::callbackOutputStars,this,_1));
        multi.multiplyNumbers(5,  10, boost::bind(&Test::callbackOutputStars,this,_1));

        // -------------- Demo 3 : global callback ----------------------

        cout << ("\n> Finally the callback from a global function :\n");
        globalCallback(boost::bind(&Test::callbackOutputStars,this,_1));

        cout << "Done" << endl;
    }

private:
    void callbackOutputStars(const std::string& str)
    {
        ostringstream oss;
        oss << "  ***** Some stars *****  " << str << endl;
        cout << oss.str();
    }

    void callbackOutputDollar(const std::string& str)
    {
        ostringstream oss;
        oss << "  $$$ Now with Dollar $$$ " << str << endl;
        cout << oss.str();
    }
};

int main()
{
    Test t;
    t.testStart();
    return 0;
}


However, if you need a callback facility are you going to know the types involved? Most of the time the answer to that question is yes. [Slightly OT: As a student, that one concept took me months to get my head around, especially with so many templates whizzing around].

boost::function does this by letting you restrict the incoming types a bit better. Think of it as a flag to other programmers about what you are doing.

#include <boost/function.hpp> // added from the last sample
// changed from last sample
void globalCallback(boost::function1<void,std::string> callback)
{
    ostringstream oss;
    oss << "From a global callback" << endl;
    callback(oss.str());
}
// changed from last sample
class Add
{
public:
    // generated ctor & dtor ok.

    bool addNumbers(int num1, int num2, boost::function1<void,std::string> callback)
    {
        ostringstream oss;
        oss << "Adding    " << num1 << " + " << num2 << " = " << (num1+num2) << endl;
        callback(oss.str());
        return true;
    }
};
// changed from last sample
class Multiply
{
public:
    // generated ctor & dtor ok.

    bool multiplyNumbers(int num1, int num2, boost::function1<void,std::string> callback)
    {
        ostringstream oss;
        oss << "Adding    " << num1 << " * " << num2 << " = " << (num1*num2) << endl;
        callback(oss.str());
        return true;
    }
};


I built both samples under MSVC6, and noticed a degradation in compile time performance using boost::function.


If you can keep you head when all about you
Are losing theirs and blaming it on you;
If you can dream - and not make dreams your master;
If you can think - and not make thoughts you aim;
Yours is the Earth and everything that's in it.

Rudyard Kipling

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.