Tải bản đầy đủ (.pdf) (644 trang)

Addison wesley professional beyond the c++ standard library an introduction to boost (2005)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2 MB, 644 trang )

BeyondtheC++StandardLibrary:AnIntroduction
toBoost
ByBjörnKarlsson
...............................................
Publisher:AddisonWesleyProfessional
PubDate:August31,2005
ISBN:0321133544
Pages:432

TableofContents|Index

IntroducingtheBoostlibraries:thenextbreakthroughinC++programming
BoosttakesyoufarbeyondtheC++StandardLibrary,makingC++programmingmore
elegant,robust,andproductive.Now,forthefirsttime,aleadingBoostexpert
systematicallyintroducesthebroadsetofBoostlibrariesandteachesbestpracticesfor
theiruse.
Writingforintermediate-to-advancedC++developers,BjörnKarlssonbrieflyoutlinesall
58Boostlibraries,andthenpresentscomprehensivecoverageof12librariesyou'relikely
tofindespeciallyuseful.Karlsson'stopicsrangefromsmartpointersandconversionsto
containersanddatastructures,explainingexactlyhowusingeachlibrarycanimproveyour
code.Heoffersdetailedcoverageofhigher-orderfunctionobjectsthatenableyoutowrite
codethatismoreconcise,expressive,andreadable.Heeventakesyou"behindthe
scenes"withBoost,revealingtoolsandtechniquesforcreatingyourowngenericlibraries.
Coverageincludes
Smartpointersthatprovideautomaticlifetimemanagementofobjectsandsimplify
resourcesharing
Consistent,best-practicesolutionsforperformingtypeconversionsandlexical
conversions
Utilityclassesthatmakeprogrammingsimplerandclearer
FlexiblecontainerlibrariesthatsolvecommonproblemsnotcoveredbytheC++
StandardLibrary


PowerfulsupportforregularexpressionswithBoost.Regex
FunctionobjectsdefinedatthecallsitewithBoost.BindandBoost.Lambda
MoreflexiblecallbackswithBoost.Function


Managedsignalsandslots(a.k.a.theObserverpattern)withBoost.Signals
TheBoostlibrariesareprovingsousefulthatmanyofthemareplannedforinclusionin
thenextversionoftheC++StandardLibrary.Getyourheadstartnow,withBeyondthe
C++StandardLibrary.
©CopyrightPearsonEducation.Allrightsreserved.


BeyondtheC++StandardLibrary:AnIntroduction
toBoost
ByBjörnKarlsson
...............................................
Publisher:AddisonWesleyProfessional
PubDate:August31,2005
ISBN:0321133544
Pages:432

TableofContents|Index













































Copyright
Foreword
Preface
Acknowledgments
AbouttheAuthor
OrganizationofThisBook
IntroductiontoBoost
StringandTextProcessing
DataStructures,Containers,Iterators,andAlgorithms
FunctionObjectsandHigher-OrderProgramming
GenericProgrammingandTemplateMetaprogramming
MathandNumerics
Input/Output
Miscellaneous
PartI.GeneralLibraries
Library1.Smart_ptr
HowDoestheSmart_ptrLibraryImproveYourPrograms?
WhenDoWeNeedSmartPointers?
HowDoesSmart_ptrFitwiththeStandardLibrary?
scoped_ptr
scoped_array
shared_ptr
shared_array
intrusive_ptr




















































































weak_ptr
Smart_ptrSummary
Endnotes
Library2.Conversion
HowDoestheConversionLibraryImproveYourPrograms?
polymorphic_cast
polymorphic_downcast
numeric_cast
lexical_cast
ConversionSummary

Library3.Utility
HowDoestheUtilityLibraryImproveYourPrograms?
BOOST_STATIC_ASSERT
checked_delete
noncopyable
addressof
enable_if
UtilitySummary
Library4.Operators
HowDoestheOperatorsLibraryImproveYourPrograms?
Operators
Usage
OperatorsSummary
Library5.Regex
HowDoestheRegexLibraryImproveYourPrograms?
HowDoesRegexFitwiththeStandardLibrary?
Regex
Usage
RegexSummary
PartII.ContainersandDataStructures
Library6.Any
HowDoestheAnyLibraryImproveYourPrograms?
HowDoesAnyFitwiththeStandardLibrary?
Any
Usage
AnySummary
Library7.Variant
HowDoestheVariantLibraryImproveYourPrograms?
HowDoesVariantFitwiththeStandardLibrary?












































































Variant
Usage
VariantSummary
Library8.Tuple
HowDoestheTupleLibraryImproveYourPrograms?
HowDoestheTupleLibraryFitwiththeStandardLibrary?
Tuple
Usage
TupleSummary
PartIII.FunctionObjectsandHigher-OrderProgramming
Library9.Bind
HowDoestheBindLibraryImproveYourPrograms?
HowDoesBindFitwiththeStandardLibrary?
Bind
Usage
BindSummary
Library10.Lambda
HowDoestheLambdaLibraryImproveYourPrograms?

HowDoesLambdaFitwiththeStandardLibrary?
Lambda
Usage
LambdaSummary
Library11.Function
HowDoestheFunctionLibraryImproveYourPrograms?
HowDoesFunctionFitwiththeStandardLibrary?
Function
Usage
FunctionSummary
Library12.Signals
HowDoestheSignalsLibraryImproveYourPrograms?
HowDoesSignalsFitwiththeStandardLibrary?
Signals
Usage
SignalsSummary
Endnotes
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin

connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales

VisitusontheWeb:www.awprofessional.com
LibraryofCongressCatalogNumber:2005927496
Copyright©2006PearsonEducation,Inc.


Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
OneLakeStreet
UpperSaddleRiver,NJ07458

TextprintedintheUnitedStatesonrecycledpaperatR.R.
DonnelleyinCrawfordsville,Indiana.
Firstprinting,August2005

Dedication
Inmemoryofthedead,inhonoroftheliving.


Foreword
GoodthingsarehappeningintheC++community.Although
C++remainsthemostwidelyusedprogramminglanguagein
theworld,itisbecomingevenmorepowerfulandyeteasierto
use.Skeptical?Bearwithme.
ThecurrentversionofstandardC++,whichwasfinalizedin
1998,offersrobustsupportfortraditionalprocedural
programmingaswellasobject-orientedandgeneric
programming.Justasold(pre-1998)C++wassingle-handedly
responsibleforputtingobject-orientedwithinthereachofthe
workadaysoftwaredeveloper,C++98hasdonethesamefor
genericprogramming.TheintegrationoftheStandardTemplate
Library(STL)intostandardC++inthemid-1990srepresented
asmuchaparadigmshiftasdidBjarneStroustrup'sadding
classestoCintheearly1980s.NowthatthemajorityofC++
practitionersareproficientwithconceptsofSTL,it'sonceagain
timetoraisethebar.
ApplicationsofthepowerofC++arestillbeingdiscovered.
Manyoftoday'sC++libraries,andmathematicallibrariesin
particular,takeroutineadvantageoftemplate
metaprogramming,afortuitousbutunforeseenresultofthe
brilliantdesignofC++templates.Ashigher-leveltoolsand

techniquescometolightintheC++community,developing
increasinglycomplexapplicationsisbecomingmore
straightforwardandenjoyable.
ItisdifficulttooverstatetheimportanceofBoosttotheworld
ofC++.SincetheratificationofC++98,noentityoutsideofthe
ISOCommitteeforStandardC++(calledWG21)hasdonemore
toinfluencethedirectionofC++thanhasBoost(andmany
BoostsubscribersareprominentmembersofWG21,including
itsfounder,myfriendBemanDawes).Thethousandsof
experiencedBoostvolunteershave,inunselfish,peer-reviewed


fashion,developedmanyusefullibrarysolutionsnotprovided
byC++98.Tenofitsofferingshavealreadybeenacceptedto
beintegratedintotheupcomingC++0xlibrary,andmoreare
underconsideration.Wherealibraryapproachhasbeenshown
tobewanting,thewisdomgainedfromthecross-pollinationof
BoostandWG21hassuggestedafewmodestlanguage
enhancements,whicharenowbeingentertained.
Intherarecasethatyouhaven'theardofBoost,letmeask…do
youneedtoconvertbetweentextandnumbersor(betteryet)
betweenanystreamabletypes?Noproblemuse
Boost.lexical_cast.Oh,youhavemoresophisticatedtext
processingrequirements?ThenBoost.TokenizerorBoost.Regex
mightbeforyou,orBoost.Spirit,ifyouneedfull-blownparsing.
Boost.Bindwillamazeyouwithitsfunctionprojectionand
compositioncapabilities.Forfunctionalprogrammingthereis
Boost.Lambda.Staticassertions?Got'em.Ifyou're
mathematicallyinclined,getyourpencilout:Youhave
Boost.Math,Graph,Quaternion,Octonion,MultiArray,Random,

andRational.Ifyouarefortunateenoughtohavediscovered
thejoyofPython,youcanuseitandC++togetherwiththe
helpofBoost.Python.Andyoucanpracticallypickyourplatform
foralloftheabove.
BjörnKarlssonisaBoostenthusiastandaheartfeltsupporterof
theC++community.Hehaspublishedusefulandwell-written
articlesintheC/C++UsersJournaland,morerecently,forThe
C++Source,anewonlinevoicefortheC++community(see
www.artima.com/cppsource).Inthisvolume,hemotivatesand
illustrateskeyBoostcomponents,andshowshowtheywork
withandextendtheC++StandardLibrary.Considerthisnot
onlyanin-depthtutorialonBoost,butalsoaforetasteofthe
futureversionofStandardC++.Enjoy!
ChuckAllison,Editor,TheC++Source


Preface
DearReader,
WelcometoBeyondtheC++StandardLibrary:AnIntroduction
toBoost.
Ifyouareinterestedingenericprogramming,librarydesign,
andtheC++StandardLibrary,thisbookisforyou.Becausethe
intendedaudienceforthebookisintermediatetoadvanced
C++programmers,thereislittlecoverageofbasicC++
concepts.Asthetitlesuggests,thefocusofthisbookisonthe
Boostlibrariesgeneralusage,bestpractices,implementation
techniques,anddesignrationale.
AlmostfromthedayIdiscoveredBoost,thepeoplebehindit,
andtheextraordinarylibrariesinit,I'vewantedtowritethis
book.ItisamazingthatalanguageasmatureasC++still

offersroomforexplorationintohigher-levelabstractionsaswell
astechnicaldetail,allwithoutrequiringchangestothe
language.Ofcourse,thisiswhatsetsC++apartfrommany
otherprogramminglanguages:Itisspecificallyandintentionally
designedforextension,andthelanguage'sfacilitiesforgeneric
constructsareextremelypowerful.Thisexplorationisatthe
coreoftheBoostlibrariesandtheBoostcommunityitself.Boost
isaboutmakingprogramminginC++moreelegant,more
robust,andmoreproductive.Asdiscoveriesaremadeandbest
practicesareshaped,agreatchallengefacestheC++
community;tosharethisknowledgewithothers.Inisolation,
thereislimitedvaluetotheseremarkablefindings,butwhen
exposedtoalargeraudience,awholeindustrywillevolve.
Thisbookshowshowtouseaselectionofthewonderfully
usefulBoostlibraries,teachesbestpracticesfortheiruse,and
evengoesbehindthescenestoseehowtheyactuallywork.
TheBoostlibraries'licensegrantspermissiontocopy,use,and


modifythesoftwareforanyuse(commercialandnoncommercial),soallyouneedtodoisvisitwww.boost.organd
downloadthelatestversion.
ForalltheC++StandardLibraryaficionadosoutthere,itiswell
knownthatanewrevisionoftheStandardLibraryisin
progress.Fromastandardizationpointofview,therearethree
primaryareaswheretheC++StandardLibraryislikelyto
change:
Fixingbrokenlibraries
Augmentingmissingfeaturestoexistinglibraries
Addinglibrariesthatprovidefunctionalitythatismissingin
theStandardLibrary

TheBoostlibrariesaddressalloftheseareasinonewayor
another.Ofthe12librariescoveredinthisbook,sixhave
alreadybeenacceptedforinclusionintheupcomingLibrary
TechnicalReport,whichmeansthattheywillmostlikelybepart
ofthenextversionoftheStandardLibrary.Thus,learning
abouttheselibrarieshasexcellentlong-termvalue.Ihopethat
youwillfindthisbooktobeavaluabletoolforusing,
understanding,andextendingtheBoostlibraries.Fromthat
vantage,you'llwanttoincorporatethoselibrariesandthe
knowledgeenshrinedwithinthemintoyourowndesignsand
implementations.That'swhatIcallreuse.
Thankyouforreading.
BjörnKarlsson


Acknowledgments
Anumberofpeoplehavemadeallthedifferenceforthisbook,
andformyabilitytowriteit.Firstofall,Iwishtothankthe
Boostcommunityfortheseastonishinglibraries.Theythe
librariesandtheBoostersmakeaveryrealdifferenceforthe
C++communityandthewholesoftwareindustry.Then,there
arepeoplewhohaveveryactivelysupportedthiseffortofmine,
andIwishtothankthempersonally.It'sinevitablethatIwill
failtomentionsome:Toallofyou,pleaseacceptmysincere
apologies.BemanDawes,thankyouforcreatingBoostinthe
firstplace,andforhookingmeupwithAddison-Wesley.Bjarne
Stroustrup,thankyouforprovidingguidanceandpointingout
importantomissionsfromthenearlyfinishedmanuscript.
RobertStewart,thankyouforthecarefultechnicalandgeneral
editingofthisbook.Robhasmadethisbookmuchmore

consistent,morereadable,andmoreaccurateandallofthison
hisfreetime!Thetechnicalerrorsthatremainaremine,not
his.Robhasalsobeeninstrumentalinfindingwaystohelpthe
readerstayontrackevenwhentheauthorstrays.Chuck
Allison,thankyouforyourcontinuousencouragementand
supportformyauthoringgoals.DavidAbrahams,thankyoufor
supportingthiseffortandforhelpingoutwithreviewing.
MatthewWilson,thankyouforreviewingpartsofthisbookand
forbeingagoodfriend.GaryPowell,thankyoufortheexcellent
reviewsandforyouroutstandingenthusiasmforthisendeavor.
AlloftheauthorsofBoostlibrarieshavecreatedonline
documentationforthem:Withoutthisgreatsourceof
information,itnearlywouldhavebeenimpossibletowritethis
book.Thankstoallofyou.ManyBoostershavehelpedoutin
differentways,andspecialthanksgotothosewhohave
reviewedvariouschaptersofthisbook.Withouttheirhelp,
importantpointswouldnothavebeenmadeanderrorswould
haveprevailed.AlekseyGurtovoy,DavidBrownell,Douglas
Gregor,DuaneMurphy,EricFriedman,EricNiebler,Fernando


Cacciola,FrankGriswold,JaakkoJärvi,JamesCurran,Jeremy
Siek,JohnMaddock,KevlinHenney,MichielSalters,Paul
Grenyer,PeterDimov,RonaldGarcia,PhilBoyd,Thorsten
Ottosen,TommySvensson,andVladimirPrusthankyouallso
much!
SpecialthanksgotoMicrosoftCorporationandComeau
Computingforprovidingmewiththeirexcellentcompilers.
Ihavealsohadthepleasureofworkingwithtwoexcellent
editorsfromAddison-Wesley.DeborahLaffertyhelpedmewith

alloftheinitialwork,suchascreatingtheproposalforthe
book,andbasicallymadesurethatIcametogripswithmany
oftheauthoringdetailsthatIwaspreviouslyobliviousto.Peter
Gordon,skillfullyassistedbyKimBoedigheimer,tookoverthe
editingofthebookandleditthroughtopublishing.Further
assistancewasgivenbyLoriLyons,projecteditor,andKelli
Brooks,copyeditor.Iwishtothankthemallformakingthe
bookpossibleandforseeingitthroughtocompletion.
FriendsandfamilyhavesupportedmyobsessionwithC++for
manyyearsnow;thankyousomuchforbeingthere,always.
Andfinally,manythankstomywifeJeanetteandourson
SimonIamforevergratefulforyourloveandsupport.Iwill
alwaysdomybesttodeserveit.


AbouttheAuthor
BjörnKarlssonworksasaSeniorSoftwareEngineerat
ReadSoft,wherehespendsmostofhistimedesigningand
programminginC++.Hehaswrittenanumberofarticlesabout
C++andtheBoostlibrariesforpublicationssuchasC/C++
UsersJournal,Overload,andtheonlinejournalTheC++
Source.
KarlssonisamemberoftheadvisoryboardforTheC++Source
andhasbeenamemberoftheeditorialboardofC/C++Users
Journal,whereheisalsooneofthecolumnistsintheExperts
Forum.HeparticipatesintheBoostnewsgroupsandisoneof
theBoost-Usersmoderators.


OrganizationofThisBook

Thisbookisdividedintothreemainparts,eachcontaining
librariespertainingtoacertaindomain,butthereisdefinitely
overlap.Thesedivisionsexisttomakeiteasiertofindrelevant
informationforyourtaskathandortoreadthebookandfind
relatedtopicsgroupedtogether.Mostofthechapterscovera
singlelibrary,butafewconsistofsmallcollections.
Thetypesettingandcodingstyleisintentionallykeptsimple.
Thereareanumberofpopularbestpracticesinthisarea,and
I'vejustpickedoneIfeelthatmostpeopleareaccustomedto,
andthatwillconveyinformationeasily.Furthermore,thecoding
styleinthisbookpurposelytriestosavesomeverticalspaceby
avoidingcurlybracesonseparatelines.
Althoughtheexamplesinmostbooksmakeheavyuseofusing
declarationsandusingdirectives,thisisnotthecasehere.I
havedonemybesttoqualifynamesintheinterestofclarity.
Thereisanadditionalbenefittodoingsointhisbook,andthat
istoshowwherethetypesandfunctionscomefrom.If
somethingisfromtheStandardLibrary,itwillbeprefixedwith
std::.Ifit'sfromBoost,itwillbeprefixedwithboost::.
Someofthelibrariescoveredbythisbookareveryextensive,
whichmakesitimpossibletoincludedetailedexplanationsofall
aspectsofthelibrary.Whenthisisthecase,there'stypicallya
notestatingthatthereismoretoknow,withreferencestothe
onlinedocumentation,relatedliterature,orboth.Also,Ihave
triedtofocusonthethingsthatareofthemostimmediateuse,
andthathaveastrongrelationwiththeC++StandardLibrary.
Thefirstpartofthisbookcoversgenerallibraries,whichare
librariesthatareeminentlyuseful,buthavenootherobvious
affinity.Theseconddiscussesimportantdatastructuresand
containers.Thethirdisabouthigher-orderprogramming.



There'snorequirementtoreadaboutthelibrariesinaspecific
order,butitcertainlydoesn'thurttofollowtraditionandstart
fromthebeginning.
Beforegettingtothein-depthlookatthecoveredBoost
libraries,asurveyofeachofthecurrentlyavailableBoost
librarieswillintroduceyoutotheBoostlibrariesandgive
contextforthosethatI'lladdressintherestofthebook.It
givesaninterestingoverviewoftheversatilityofthisworldclasscollectionofC++libraries.


IntroductiontoBoost
Becauseyouarereadingthisbook,Iexpectthatyouare
somewhatfamiliarwiththeBoostlibraries,orthatyouatleast
haveheardofBoost.Thereareagreatnumberoflibrariesin
Boost,andtherearefew,ifany,thatwillnotbeofatleast
someinteresttoyou.Asaresult,youwillmostdefinitelyfind
librariesyoucanputtoimmediateuse.TheBoostlibraries
rangeoverawidevarietyofdomainsfromnumericlibrariesto
smartpointers,fromalibraryfortemplatemetaprogrammingto
apreprocessorlibrary,fromthreadingtolambdaexpressions,
andsoon.AlloftheBoostlibrariesarecompatiblewithavery
generouslicense,whichensuresthatthelibrariescanbefreely
usedincommercialapplications.Supportisavailablethrough
newsgroups,wheremuchoftheactivityoftheBoost
communitytakesplace,andthereisatleastonecompanythat
specializesinconsultingrelatedtotheBoostlibraries.Foran
onlineintroductiontotheBoostcommunity,Istronglysuggest
thatyouvisitBoostontheWebatwww.boost.org.

Asofthetimeofthiswriting,thecurrentBoostreleaseis
1.32.0.Init,thereare58separatelibraries.Thefollowing
pagesintroduceall58ofthoselibrariessortedbycategoryand
giveashortdescriptionofwhatthelibrarieshavetooffer.For
thelibrariesnotcoveredindetailinthisbook,havealookat
thedocumentationprovidedatwww.boost.org,whichisalso
whereyougotodownloadtheBoostlibraries.


StringandTextProcessing
Boost.Regex
Regularexpressionsareessentialforsolvingagreatnumberof
pattern-matchingproblems.Theyareoftenusedtoprocess
largestrings,findinexactsubstrings,tokenizeastring
dependingonsomeformat,ormodifyastringbasedoncertain
criteria.ThelackofregularexpressionssupportinC++has
sometimesforceduserstolookatotherlanguagesknownfor
theirpowerfulregularexpressionsupport,suchasPerl,awk,
andsed.Regexprovidesefficientandpowerfulregular
expressionsupport,designedonthesamepremisesasthe
StandardTemplateLibrary(STL),whichmakesitintuitiveto
use.RegexhasbeenacceptedfortheupcomingLibrary
TechnicalReport.Formoreinformation,see"Library5:Regex."
TheauthorofRegexisDr.JohnMaddock.

Boost.Spirit
TheSpiritlibraryisafunctional,recursive-decentparser
generatorframework.Withit,youcancreatecommand-line
parsers,evenalanguagepreprocessor.[1]Itallowsthe
programmertospecifythegrammarrulesdirectlyinC++code,

using(anapproximationof)EBNFsyntax.Parsersaretypically
hardtowriteproperly,andwhentargetedataspecificproblem,
theyquicklybecomehardtomaintainandunderstand.Spirit
avoidstheseproblems,whilegivingthesameornearlythe
sameperformanceasahand-tunedparser.
[1]TheWavelibraryillustratesthispointbyusingSpirittoimplementahighlyconformantC++preprocessor.


TheauthorofSpiritisJoeldeGuzman,togetherwithateamof
skilledprogrammers.

Boost.String_algo
Thisisacollectionofstring-relatedalgorithms.Therearea
numberofusefulalgorithmsforconvertingcase,trimming
strings,splittingstrings,finding/replacing,andsoforth.This
collectionofalgorithmsisanextensiontothoseintheC++
StandardLibrary.
TheauthorofString_algoisPavolDroba.

Boost.Tokenizer
Thislibraryofferswaysofseparatingcharactersequencesinto
tokens.Commonparsingtasksincludefindingthedatain
delimitedtextstreams.Itisbeneficialtobeabletotreatsucha
sequenceasacontainerofelements,wheretheelementsare
delimitedaccordingtouser-definedcriteria.Parsingisa
separatetaskfromoperatingontheelements,anditisexactly
thisabstractionthatisofferedbyTokenizer.Theuser
determineshowthecharactersequenceisdelimited,andthe
libraryfindsthetokensastheuserrequestsnewelements.
TheauthorofTokenizerisJohnBandela.



DataStructures,Containers,Iterators,and
Algorithms
Boost.Any
TheAnylibrarysupportstypesafestorageandretrievalof
valuesofanytype.Whentheneedforavarianttypearises,
therearethreepossiblesolutions:
Indiscriminatetypes,suchasvoid*.Thissolutioncanalmost
neverbemadetypesafe;avoiditliketheplague.
Varianttypesthatis,typesthatsupportthestorageand
retrievalofasetoftypes.
Typesthatsupportconversions,suchasbetweenstring
typesandintegraltypes.
Anyimplementsthesecondsolutionavalue-basedvarianttype,
withanunboundedsetofpossibletypes.Thelibraryisoften
usedforstoringheterogeneoustypesinStandardLibrary
containers.Readmorein"Library6:Any."
TheauthorofAnyisKevlinHenney.

Boost.Array
ThislibraryisawrapperaroundordinaryC-stylearrays,
augmentingthemwiththefunctionsandtypedefsfromthe
StandardLibrarycontainers.Ineffect,thismakesitpossibleto
treatordinaryarraysasStandardLibrarycontainers.Thisis


usefulbecauseitaddssafetywithoutimpedingefficiencyandit
enablesuniformsyntaxforStandardLibrarycontainersand
ordinaryarrays.Thelattermeansthatitenablestheuseof

ordinaryarrayswithmostfunctionsthatrequireacontainer
typetooperateon.Arrayistypicallyusedwhenperformance
issuesmandatethatordinaryarraysbeusedratherthan
std::vector.
TheauthorofArrayisNicolaiJosuttis,whobuiltthelibraryupon
ideasbroughtforthbyMattAusternandBjarneStroustrup.

Boost.Compressed_pair
Thislibraryconsistsofasingleparameterizedtype,
compressed_pair,whichisverysimilartotheStandardLibrary's
std::pair.Thedifferencefromstd::pairisthat
boost::compressed_pairevaluatesthetemplateargumentstoseeif
oneofthemisemptyand,ifso,usestheemptybase
optimizationtocompressthesizeofthepair.
Boost.Compressed_pairisusedforstoringapair,whereoneor
bothofthetypesispossiblyempty.
TheauthorsofCompressed_pairareSteveCleary,Beman
Dawes,HowardHinnant,andJohnMaddock.

Boost.Dynamic_bitset
TheDynamic_bitsetlibraryverycloselyresemblesstd::bitset,
exceptthatwhereasstd::bitsetisparameterizedonthenumber
ofbits(thatis,thesizeofthecontainer),boost::dynamic_bitset
supportsruntimesizeconfiguration.Althoughdynamic_bitset
supportsthesameinterfaceasstd::bitset,itaddsfunctionsthat
supportruntime-specificfunctionalityandsomethataren't


availableinstd::bitset.Thelibraryistypicallyusedinsteadof
std::bitset,inscenarioswherethesizeofthebitsetisn't

necessarilyknownatcompiletime,ormaychangeduring
programexecution.
TheauthorsofDynamic_bitsetareJeremySiekandChuck
Allison.

Boost.Graph
Graphisalibraryforprocessinggraphstructures,usinga
designheavilyinfluencedbytheSTL.Itisgenericandhighly
configurable,andincludesdifferentdatastructures:adjacency
lists,adjacencymatrices,andedgelists.Graphalsoprovidesa
largenumberofgraphalgorithms,suchasDijsktra'sshortest
path,Kruskal'sminimumspanningtree,topologicalsort,and
manymore.
TheauthorsofGraphareJeremySiek,Lie-QuanLee,and
AndrewLumsdaine.

Boost.Iterator
Thislibraryprovidesaframeworkforcreatingnewiterator
types,anditalsooffersanumberofusefuliteratoradaptors
beyondthosedefinedbytheC++Standard.Creatingnew
iteratortypesthatconformtothestandardisadifficultand
tedioustask.Iteratorsimplifiesthattaskbyautomatingmostof
thedetails,suchasprovidingtherequiredtypedefs.Iteratoralso
makesitpossibletoadaptanexistingiteratortypetogiveit
newbehavior.Forexample,theindirectiteratoradaptorapplies
anextradereferencingoperation,makingitpossibletotreata
containerofpointers(orsmartpointers)toatypeasifit
containedobjectsofthattype.



TheauthorsofIteratorareJeremySiek,DavidAbrahams,and
ThomasWitt.

Boost.MultiArray
MultiArrayprovidesamultidimensionalcontainerthatclosely
resemblestheStandardLibrarycontainersandismore
effective,efficient,andstraightforwardthanvectorsofvectors.
Thedimensionsofthecontaineraresetatdeclarationtime,but
thereissupportforslicingandprojectingdifferentviews,and
alsoruntimeresizingofthedimensions.
TheauthorofMultiArrayisRonaldGarcia.

Boost.Multi-index
Multi-indexoffersmultipleindicesintoanunderlyingcontainer.
Thismeansthatitispossibletohavedifferentsortingorders
anddifferentaccesssemanticsforoneunderlyingcontainer.
Boost.Multi-indexisusedwhenstd::setandstd::mapisn't
enough,oftenduetotheneedofmaintainingmultipleindices
forefficientelementretrieval.
TheauthorofMulti-indexisJoaquínMLópezMuñoz.

Boost.Range
Thislibraryisacollectionofconceptsandutilitiesforranges.
Ratherthanhavingalgorithmsbespecifiedintermsofpairsof
iteratorsfordenotingranges,usingrangesgreatlysimplifiesthe
useofalgorithmsandraisestheabstractionlevelofusercode.
TheauthorofRangeisThorstenOttosen.


Boost.Tuple

PairsareavailableinStandardC++(fromtheclasstemplate
std::pair),butthereiscurrentlynosupportforn-tuples.Enter
Tuple.Unlikewhenusingstructsorclassesfordefiningn-tuples,
theclasstemplatetuplesupportsdirectdeclarationanduseas
functionreturntypeorargument,andprovidesagenericwayof
accessingthetuple'selements.See"Library8:Tuple8"forthe
detailsofthisgreatlibrary.Tuplehasbeenacceptedforthe
upcomingLibraryTechnicalReport.
TheauthorofTupleisJaakkoJärvi.

Boost.Variant
TheVariantlibrarycontainsagenericdiscriminatedunionclass
forstoringandmanipulatinganobjectfromasetof
heterogeneoustypes.Auniquefeatureofthelibraryisthe
supportfortype-safevisitation,whichalleviatesthecommon
problemoftype-switchingcodeforvariantdatatypes.
TheauthorsofVariantareEricFriedmanandItayMaman.


FunctionObjectsandHigher-Order
Programming
Boost.Bind
BindisageneralizationoftheStandardLibrarybinders,bind1st
andbind2nd.Thelibrarysupportsbindingargumentstoanything
thatbehaveslikeafunctionfunctionpointers,functionobjects,
andmemberfunctionpointerswithauniformsyntax.Italso
enablesfunctionalcompositionbymeansofnestedbinders.
Thislibrarydoesnothavealloftherequirementsthatare
imposedbytheStandardLibrarybinders,mostnotablythat
thereisoftennoneedtoprovidethetypedefsresult_type,

first_argument_type,andsecond_argument_typeforyourclasses.This
libraryalsomakesitunnecessarytousetheadaptorsptr_fun,
mem_fun,andmem_fun_ref.TheBindlibraryisthoroughlycoveredin
"Library9:Bind9."It'sanimportantandveryusefuladditionto
theC++StandardLibrary.Bindistypicallyusedwiththe
StandardLibraryalgorithms,andisoftenusedtogetherwith
Boost.Function,yieldingapowerfultoolforstoringarbitrary
functionsandfunctionobjectsforsubsequentinvocation.Bind
hasbeenacceptedfortheupcomingLibraryTechnicalReport.
TheauthorofBindisPeterDimov.

Boost.Function
TheFunctionlibraryimplementsageneralizedcallback
mechanism.Itprovidesforthestorageandsubsequent
invocationoffunctionpointers,functionobjects,andmember
functionpointers.Ofcourse,itworkswithbinderlibrariessuch
asBoost.BindandBoost.Lambda,whichgreatlyincreasesthe


×