• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Exploring C++ Through Example and Practice - Part I
 

Exploring C++ Through Example and Practice - Part I

on

  • 715 views

c

c

Statistics

Views

Total Views
715
Views on SlideShare
710
Embed Views
5

Actions

Likes
6
Downloads
42
Comments
2

3 Embeds 5

http://localhost 3
http://staging.slideshare.com 1
http://htmledit.squarefree.com 1

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

12 of 2 previous next

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Within a particular sublanguage, the rules are straightforward and easy to remember. But when you move from one sublanguage to another, however the rules may change.
  • #define ASPECT_RATIO 1.653Symbolic name not entered in the symbol table. Errors involving the constant will not expose the symbol name. Also this will result in smaller executable code. The preprocessor’s blind substitution of macro ASPECT_RATIO with 1.653 will result in multiple copies of 1.653 in your object code. The use of the constant AspectRatio should never result in more than one copy.
  • When you need the value of the class constant during compilation of the class, such as in the declaration of the array GamePlayer::scores above (where compilers insist on knowing the size of the array during compilation), then the accepted way to compensate for compilers that (incorrectly) forbid the in-class specification of initial values for static integral class constants is to use the “enum hack”Also you can take the address of a constant but not an enum. This enforces the constraint that prevents people get a pointer or reference to one of your integral constants
  • The template generates a whole family of functions, each of which takes two objects of the same type and calls f with greater of the two objects. There’s no need to parenthesize parameters inside the function body, no need to worry about evaluating parameters inside the function body multiple times, etc.Also, callWithMax obeys scope and access rules , being a function.
  • dynamic_cast is used to perform safe casts down or across an inheritance hierarchy in such a way that it lets us know If the cast succeeded.It is also used to find the beginning of memory occupied by an object. Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references). They cannot be applied to types that lack virtual functions.Reinterpret casts are rarely portable. Most common use of reinterpret_cast is to cast between function pointer types.typedef void (*FuncPtr)();FuncPtrfuncPtrArray[10];intdoSomething();funcPtrArray[0]=reinterpret_cast(&doSomething);
  • Using const with STL iterators:std::vector vec;…const std::vector::iteratoriter= vec.begin();*iter = 10;++iter; //error , iter is conststd::vector::const_iteratorcIter = vec.begin();*cIter = 10; //error; *cITer is constant++Iter;Class Rational {…};const Rational operator* (const Rational& lhs, const Rational& rhs);Rational a, b, c;If (a*b=c) … //typo Overloaded const and non-const functions:Class TextBlock {Public: …Cont char& operator[](std::size_t position) const{ return text[position]; }Char& operator[] (std::size_t position){ return text[position]; }Private: Std::String text;};Bitwise and Logical constness:Bitwise const camp believes that a member function is const iff it doesn’t modify any of the object’s data members (excluding those that are static), i.e if it doesn’t modify any of the bits inside the object. Logical constness: define variables as ‘mutable’ which need to change within a const member function and is yet part of it.Class TextBlock {Public:…Const char& operator[](std::size_t position) const{…Return text[position];}Char& operator[](std::size_t position){Return const_cast(static_cast(*this)[position]);}…};
  • File 1:Class FileSystem {Public:…Std::size_tnumDisks() const;…};Extern FileSystemtfs;**********************************File 2:Class Directory {Public: Directory(params);…};Directory::Directory(params){…Std::size_t disks = tfs.numDisks();…}********************************Class FileSystem {…};FileSystem& tfs(){Static FileSystemfs;Return fs;}Class Directory {…};Directory::Directory(params){…Std::size_t disks = tfs().numDisks();…}Directory& tempDir(){Static Directory td(params);Return td;}
  • Class Empty{};Is equivalent to:Class Empty {Public:Empty() {…}Empty(Const Empty& rhs) {…}~Empty() { …}Empty& operator=(const Empty& rhs) {…}};*************************************The generated destructor is non-virtual.The copy constructor and the copy assignment operator simply copy each non-static data member of the source object over to the target object.If any constructor is already defined by a user, the compiler does not go out of the way to define a default constructor for the user and overriding the user’s intent.*******************Scenarios where compiler fails to generate the copy assignment operator:Presence of reference/consts inside the classIncase , copy assignment operator is declared private in the base class.
  • Class Uncopyable {Protected:Uncopyable() {}~Uncopyable() {}Private:Uncopyable(const Uncopyable&);Uncopyable& operator=(const Uncopyable);};Class HomeFoeSale: private Uncopyable {…};
  • 1. Any class with at least one virtual member function should have a virtual destructor2. Exceptions in destructors lead to undefined behavior3. They invariably call the base class functions and not the derived class functions as the base class constructor executes before the derived class constructor4. While writing a copy constructor ensure the base class constructor is called before copying the derived class field values.
  • Derived class object must contain information to indicate the function to be called at run-time. The compiler converts the name of the virtual function into an index into a table of pointers to functions. That table is usually called “A virtual function table” /vtbl . Each class with virtual functions has its own vtbl identifying its virtual functions. Space overhead is one pointer in each object of a class with virtual functions plus one vtbl for each such class
  • Example of a template:Template class String {structSrep;Srep* rep;Public: String(); String(const C*); String(const String&); C read(inti ) const;//…};
  • Also HashMap

Exploring C++ Through Example and Practice - Part I Exploring C++ Through Example and Practice - Part I Presentation Transcript

  • Exploring C++Presenter:- Subhendra Basu (SysTools Team)
  • Background CheckFamiliarity with basic imperative programmingconceptsVariables (scoping, global/local)LoopsFunctions and function abstractionPrior experience with OOP and knowledge ofbasic OOP concepts(inheritance, overloading, etc.)4/18/2013
  • Session Outline**A brief overview ofbasic C++ conceptsOverview of STLOverview of BoostTemplatesException HandlingBest PracticesQuestions andReferences4/18/2013
  • Which ProgrammingLanguage is the fastest ?http://shootout.alioth.debian.org/u32q/which-programming-languages-are-fastest.php 4/18/2013
  • Binary CodeAssembly LanguagesProcedural Languages (C, Fortran, COBOL…)OO Languages ( C++, Java, Python…)Declarative languages (Haskell, ML, Prolog…)?Towards a higher level ofabstraction4/18/2013
  • Current Status of C++Current day C++ cannot be regarded as “thelanguage C with classes”C++ is a federation of languages that supportsProceduralObject OrientedFunctionalGenericMetaprogramming features4/18/2013
  • Primary ProgrammingParadigms in C++C : Blocks, Statements, Preprocessor, Built-in DataTypes, Arrays, PointersObject Oriented C++ :classes, encapsulation, inheritance, polymorphism, virtual functions (dynamic binding)Template C++ : Generic Programming part of C++(also known as Template Metaprogramming)The Standard Template LibraryCaution: Rules for Effective C++ Programming varydepending on the part of C++ you are using4/18/2013
  • Section I:C++ Basics through BestPractices4/18/2013
  • {Const, Enum, Inline} vs#definePrefer the compiler to the preprocessorDefining a constant or a macro through a hashdefine is risky. Compiler errors may point to thevalue of the constant and not the variable used todefine the constant making debugging difficult.Instead use „const‟ or „enum‟Macros can be rewritten as inline function toavoid side-effects4/18/2013
  • The „enum‟ hackConsider the code:Class GamePlayer {private:static const int NumTurns = 5;enum { NumTurns = 5 };int scores[NumTurns];…}4/18/2013
  • Move over C macros// call f with maximum of a and b#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a):(b))int a=5; b=0;CALL_WITH_MAX(++a, b); //a is incremented twiceCALL_WITH_MAX(++a, b+10); //a is incremented onceBetter way:template <typename T>inline void callWithMax(const T& a, const T& b){f(a>b?a:b);}4/18/2013
  • Pointers vs ReferencesPointersCan be nullMay not be initializedat the point of definitionCan be assigned todifferent objects atdifferent points of time.ReferencesNothing called as a “null”reference. Always points toan objectIt is compulsory to initializea reference when definingitThe object it points tocannot be changed on thefly. It keeps pointing to thevalue it was initialized with.More efficient to use thanpointers as there need notbe any run-time typechecking to validatewhether it is null or not 4/18/2013
  • Prefer C++ style castsEasier to parse for humans and toolsAllows compilers to catch casting errors whichotherwise would go undetectedFour types of casting are supported:static_castconst_castreinterpret_castdynamic_cast4/18/2013
  • Use const wheneverpossibleDeclaring something „const‟ helps compilers detectusage errors. const can be applied to objects at anyscope, to function parameters and return types, andto member functions as a whole.Compilers enforce bitwise or physical constness, butyou should program using logical or conceptualconstnessWhen const and non-cost member functions haveessentially identical implementation, code duplicationcan be avoided by having the non-const version callthe const version4/18/2013
  • Make sure objects areinitialized before they are usedReading uninitialized values yields undefinedbehaviorManually initialize objects of built-in type, becauseC++ only sometimes initializes them itself.In a constructor, prefer use of the memberinitialization list to assignment inside the body of theconstructor. List data members in the initialization listin the same order they‟re declared in a class.Avoid initialization order problems across translationunits by replacing non-local static objects with localstatic objects4/18/2013
  • Never treat ArraysPolymorphicallyThe result of deleting an array of derived classobjects through a base class pointer isundefined.Polymorphism and pointer arithmetic don‟t mix4/18/2013
  • ClassesA class is like a cookie cutter; it defines theshape of the objectsObjects are like cookies; they are instances ofthe class4/18/2013
  • What C++ silently writes andcallsDefining an empty class incites the compiler todeclare its own versions of copy constructor, copyassignment operator, and a destructor and also adefault constructor. All these functions will be bothpublic and inline.These functions are generated only if they areneededE.g. class Empty {};Empty e1; //default constructor//destructorEmpty e2(e1); //copy constructorE2=e1; copy assignment operator4/18/2013
  • Explicitly disallow the use ofcompiler-generated functionsyou do not wantDeclare the functions (Copyconstructor/assignment operator) but declarethem private.But member and friend functions still haveaccess to thisSo declare them but don‟t define them. (gives alink time error when called)Possible to move the link time error to compiletime.Privately Inherit from a class that is uncopyable. 4/18/2013
  • 1. Declare destructors virtual in polymorphicbase classes2. Avoid default constructors where they arenot needed3. Prevent exceptions from leavingdestructors4. Never call virtual functions duringconstruction or destruction5. Have assignment operators return areference to *this6. Handle assignment to self in operator=7. Copy all parts of an objectMiscellaneous best practices inC++4/18/2013
  • Inheriatance and Access toBase ClassesClass X: public B { /**/}Class Y: protected B { /**/}Class Z: private B { /**/}4/18/2013
  • When B is a public base, its public members can beused by any function. Its protected members can beused by members and friends of D and members andfriends of classes derived from D. Any function canconvert a D* to a B*When B is a protected base, its public and protectedmembers can be used only by member functions andfriends of classes derived from D and by memberfunctions and friends of classes derived from D. Onlyfriends and members of D and friends and membersof classes derived from D can convert D* to B*When B is a private base, its public and protectedmembers can be used only by member functions andfriends of D. Only friends and members of D canconvert D* to B*4/18/2013
  • Virtual Function :Mechanism4/18/2013StackList_stack Array_stack
  • Virtual Functions (contd)4/18/2013Array_stack::pushArray_stack::popList_stack::pushList_satck::popArray_stackobjectList_stack objectvtblvtbl
  • Liskov SubstitutionPrinciplehttp://www.pmg.csail.mit.edu/~liskov/..(Barbara Liskov Winner,Turing Award 08‟ )If S is a subtype of T, then the behavior of aprogram P must remain unchanged when objectsof type T are replaced with objects of type S.4/18/2013
  • Memory Management :auto_ptrPrevent memory leaks by using auto_ptr (smartpointer) whose destructor calls delete on what itpoints to.std::auto_ptr<Investment>pInv(createInvestment());o There should not be more than one auto_ptrpointing to an object as this would lead to multipledeletion and undefined behavioro auto_ptrs have the property that if they are copiedusing copy constructor or copy assignment operator,this sets them to null and the copying pointerassumes sole ownership of the resource4/18/2013
  • auto_ptr copying examplestd::auto_ptr<Investment>pInv1(createInvestment()); //pInv1 points to theobject returned from createInvestmentstd::auto_ptr<Investment> pInv2(pInv1);//pInv2 points to the object, pInv1is nullpInv1 = pInv2;4/18/2013
  • Memory Management:shared_ptrA reference counting smart pointer (RCSP) keepstrack of how many objects point to a particularresource and automatically deletes the resourcewhen nobody is pointing to it any longer. RCSPs offerbehavior similar to garbage collection.TR1‟s shared::ptr and boost::shared_ptr areexamples of RCSPsBoth auto_ptr and tr1::shared_ptr use delete in theirdestructors, not delete[] so cannot be used withdynamically allocated arrays.However Boost has boost::scoped_array andBoost::shared_array have the required behavior4/18/2013
  • Section II :TemplateMetaprogramming4/18/2013
  • What are templates and whyTemplates ?Templates are functions or classes written forone or more types not yet specifiedExtensive Application, the C++ STL librarymakes heavy use of templatesIt is usually a good idea to debug a particularclass, such as String, before turning it into atemplate String<C>. This is done for ease ofdebugging4/18/2013
  • Template InstantiationThe process of generating a class declarationfrom a template class and a template argumentis called template instantiationA version of a template for a particular templateargument is called a specializationTemplates provide a powerful way of generatingcode from relatively short definitions. So it has tobe used with caution lest the memory will beflooded by almost identical function definitions4/18/2013
  • Function TemplatesFunction templates are essential for writing genericalgorithms to be applied to a wide variety of containertypes. The ability to deduce the template argumentsfor a call from the function arguments is crucial.However class template parameters are neverdeduced. This is because the flexibility provided byseveral constructors for a class make such adeduction impossible in many cases and obscure inmany more.Example:template <class T> void sort(vector<T>& v) {//…} 4/18/2013
  • Function Template overloadingIt is possible to declare several functiontemplates with the same name and even declarea combination of function templates and ordinaryfunctions with the same name.Example:template<class T> T sqrt(T);template<class T> complex<T>sqrt(complex<T>);double sqrt(double);4/18/2013
  • Function Templates (contd)void f(complex<double> z){sqrt(2); //sqrt<int> (int)sqrt(2.0); //sqrt(double)sqrt(z);//sqrt<double>(complex<double>)}4/18/2013
  • Using template arguments tospecify policyConsider string sorting program. Three concepts areinvolved: string, element type and the comparison“policy”.Take for example, sorting swedish names:template<class T, class C>int compare(const String<T>& str1, const String<T>&str2) {for (int i=0; i<str1.length() && i<str2.length(); i++) {if (!C::eq(str1[i], str2[i])) return C::lt(str1[i],str2[i])? -1:1;return str1.length()-str2.length();}4/18/2013
  • Sorting Policy (contd)The Comparison Policy:template<class T> class Cmp {public:static int eq(T a, T b) {returna==b;}static int lt(T a, T b) { returna<b;}};class Literate {public:static int eq(char a, char b){return a==b;}static int lt(char, char); //tablelookup based on character value};Void f(String<char> swede1, String<char>swede2){compare<char, Cmp<char>(swede1, swede2);compare(char, Literate>(swede1, swede2);}4/18/2013
  • Default TemplateParameterstemplate<class T, class C = Cmp<T> >Int compare(const String<T>& str1, const String<T>&str2) {//…}Void f(String<char> swede1, String<char> swede2) {Compare(swede1, swede2); //use Cmp<char>}4/18/2013
  • Template SpecializationBy default, a template gives a single definition tobe used for every template argument that ispossible.In template specialization, an alternativedefinition is provided for a type supplied by theuser. This increases run-time efficiency byavoiding code bloat and maximizing the amountof shared code4/18/2013
  • Complete SpecializationTemplate<> class Vector <void*> {void** p;//void*& operator[](int i);}4/18/2013
  • Partial SpecializationTemplate<class T>class Vector<T*>: privateVector<void*>{};Vector<Shape*> vps; //T= ShapeVector<int**> vppi; // T=int*4/18/2013
  • Order of SpecializationTemplate<class T>class Vector; //generalTemplate<class T>class Vector<T*>; specialized forany pointerTemplate<> class Vector<void*>; //specialized forvoid*4/18/2013
  • Power of Templatestemplate <unsigned n> struct Factorial {enum { value = n* Factorial<n-1>::value};};template<> struct Factorial<0> {enum {value=1};};4/18/2013
  • Section III:Exception Handling4/18/2013
  • ExceptionsAn exception is an object of some classrepresenting an exceptional occurrence.Code that detects an error “throws” an objectA piece of code expresses its desire to handleexception by a catch clause.The effect of a “throw” is to unwind the stackuntil a suitable “catch” is found4/18/2013
  • Catching ExceptionsVoid f() {try {throw E();}catch(H) {}}4/18/2013
  • Catching Exceptions(conditions)The handler is invoked:1. If H is the same type as E2. If H is an unambiguous base of E3. If H and E are pointer types and [1] or [2] holdsfor the types to which they refer4. If H is a reference and [1] or [2] holds for the typeto which H refers4/18/2013
  • Re-ThrowVoid h() {try {//code that might throw Math Errors}catch(Matherr) {if (can handle_it_completely) {// handle the Matherrreturn;} else {throw; //rethrow the exception}}}4/18/2013
  • Catch Every Exceptionvoid m() {try {}catch(…) {throw;}4/18/2013
  • Section II :Overview of STL4/18/2013
  • STL BasicsSTL stands for Standard Template Library. STL isthe invention of Dave Musser, Alex Stepanov andMeng Lee.The main components of STL are:Containers, Iterators and AlgorithmsContainers are used to manage objects of acertain kind. Iterators are used to step throughthe containers. Algorithms are used to processthe above collections of objects4/18/2013
  • STL ComponentsContainerContainerContainerAlgorithmsIteratorIterator4/18/2013
  • ContainersThere are two kinds of containers:Sequence Containers: These are orderedcollections where each element has a certainposition.STL has three predefined sequence containers:dequeue, vector and listAssociative Containers: These are sortedcollections in which the position of the elementdepends on its value due to a certain sortingcriterion. STL ahs four predefined containerclasses: set, multiset, map, multimap4/18/2013
  • Iteratoriterating over elements of alistBegin()End()Pos++4/18/2013
  • Set with six elements42 61 3 54/18/2013
  • QuizGiven a vector<int> v,what is the difference between the lines marked Aand B?void f(vector<int>& v) {v[0] ; // Av. at(0) ; // B}4/18/2013
  • Section IIIBOOST4/18/2013
  • Library I: smart_ptrAutomatic lifetime management of objects withshared_ptr makes shared ownership ofresources effective and safeSafe observation of shared resources throughweak_ptr avoids dangling pointersScoped resources using scoped_ptr andscoped_array make the code easier to write andmaintain, helps in writing exception free code4/18/2013
  • Boost/scoped_ptr.hppBoost::Scoped_ptr is used to ensure the properdeletion of a dynamically allocated object.Scoped_ptr is similar to auto_ptr but it doesn‟ttransfer ownership as auto_ptr doesA scoped ptr cannot be copied or assigned at allCaution: Never ever store auto_ptr in standardlibrary containers. Usually you get compiler error.If not, then you are in trouble.4/18/2013
  • Scoped_ptr = constauto_ptr ?The difference is that ascoped pointer can bereset, effectively deleting andreplacing the pointee whenneeded4/18/2013
  • Boost/scoped_array.hppScoped arrays do for arrayswhat scoped_ptr do forpointers to single objects4/18/2013
  • Boost/shared_ptr.hppIt is a reference counted smart pointer thateliminates the need to write complicated logic tocontrol the lifetime of objects shared among twoor more objects.RCSPs can be categorized as “intrusive” and“non-intrusive”. The former expects the classeswhich it manages to provide certain functionalityto manage the reference count4/18/2013
  • Boost/shared_array.hppShared_arrays is a smartpointer that enablesshared ownership ofarrays4/18/2013
  • Library II: ConversionUnderstandable, maintainable and consistentpolymorphic conversionsStatic downcasting using safer constructs thanstatic_castRange preserving numeric conversions thatensure correct value logic and less timedebuggingCorrect and reusable lexical conversions thatlead to less time coding4/18/2013
  • Polymorphic_castSame as dynamic cast but always throwstd::bad_cast exception in case of failureC++ dynamic cast returns null pointer in case offailed conversion of a pointer and returnsstd::bad_cast in case of failed conversion of areference4/18/2013
  • Boost/cast.hppNumeric casts ensure that conversions betweennumeric types (char, int , float, etc) are valid andlegal or they are not allowedUsage:char c=boost: : numeric_cast<char>(12) ;float f=boost: : numeric_cast<float>( 3. 001) ;4/18/2013
  • Boost/lexical_cast.hppThis handles conversions to and from string type ()Usage:std: : string s=" 42 ";int i=boost: : lexical_cast<int>(s) ;// float to stringfloat f=3 . 14151;s=boost: : lexical_cast<std: : string>(f) ;4/18/2013
  • Library 3: UtilityCompile time assertions withBOOST_STATIC_ASSERTSafe destruction with checked_delete andchecked_array_deleteProhibition of copying with noncopyableRetrieval of object addresses when operator& isoverloaded through addressofControlled participation of overloads andspecializations withenable_if and disable_if4/18/2013
  • Boost/static_assert.hTo enforce assertions during compile timeUsage:#include <iostream>#include " boost/type_traits. hpp“#include " boost/static_assert. hpp“template <typename T> classonly_compatible_with_integral_types {BOOST_STATI C_ASSERT(boost: : is_integral<T>: :value) ;} ;4/18/2013
  • Boost/checked_Delete.hppWhen deleting an object through a pointer, theresult is typically dependent on whether the typebeing deleted is known at the time of thedeletion. There are hardly ever compilerwarnings when deleting a pointer to anincomplete type, but it can cause all kinds oftrouble, because the destructor may not beinvoked. This, in turn, means that cleanup codewon‟t be performed. checked_delete is in effect astatic assertion that the class type is known upondestruction, enforcing the constraint that thedestructor will be called.4/18/2013
  • Usage: checked delete#include " boost/checked_delete. hpp“class some_class;some_class* create() {return (some_class*) 0;}int main(){some_class* p2=create() ;boost: : checked_delete(p2 ) ;}4/18/2013
  • Noncopyable(boost/utility.hpp)It prohibits access to the copy constructor andassignment operator of a class which derives fromthe class noncopyableUsage:#include " boost/utility. hpp“class please_dont_make_copies : boost: : noncopyable { } ;int main() {please_dont_make_copies d1;please_dont_make_copies d2(d1) ;please_dont_make_copies d3;d3=d1;}4/18/2013
  • Boost::addressof(boost/utility.hpp)Used to get the address of objects (like the & operator)Is useful when & operator Is overloadedUsage:#include " boost/utility. hpp“class some_class { } ;int main(){some_class s;some_class* p=boost: : addressof(s) ;}4/18/2013
  • boost/utility/enable_if. hppenable_if/disable_ifControls whether a certainfunction or templatespecialization can participatein overload resolutionprocess4/18/2013
  • Usage (enable_if):#include <iostream>#include " boost/utility/enable_if. hpp“#include " boost/type_traits. hpp“#include " boost/mpl/has_xxx.hpp“BOOST_MPL_HAS_XXX_TRAIT_DEF(type);void some_func( int i){std: : cout << " void some_func(" << i << " ) n";}4/18/2013
  • Usage(contd)template <typename T> void some_func(Tt,typename boost: : enable_if<has_type<T> >: :type* p=0) {typename T: : type variable_of_nested_type;std: : cout << " template <typename T> voidsome_func( T t) n" ;}4/18/2013
  • Library IV: Regex(boost/regex.hpp)Usage:boost: : regex reg( " (A. * ) ") ;bool b=boost: : regex_match(" This expressioncould match from A and beyond. ",reg) ;4/18/2013
  • Library V: Any(boost/any.hpp)Usage:boost::any a;a=std::string(“A string”);A=42;A=3.1415;btd:string S= boost::any_cast<std::string>(a);//throws boost::bad_Any_cast4/18/2013
  • Library VI: Variant(boost/variant.hpp)Usage:boost::variant <int, std::string,double>my_first_variant(“Hello World”);my_first_variant = 2;my_first_variant= 4.52;my_first_variant= “Fabulous”;my_first_variant = 0;assert(boost::get<int>(my_first_variant)==0);4/18/2013
  • Library VII: Tuple(boost/tuple/tuple.hpp)Allows grouping of values upto 10 elements asagainst 2 elements provided by STLUsage:boost: : tuple<int, double, std: : string>triple(42, 3. 14, " My first tuple! " ) ;4/18/2013
  • Library VIII: bindUsage:#include <iostream>#include " boost/bind. hpp“void nine_arguments(int i1, int i2 , int i3, int i4,int i5, int i6 , inti7, int i8, int i9){std: : cout << i1 << i2 << i3 << i4 << i5 < < i6 << i7 << i8 << i9 << n ;}4/18/2013
  • Usage (contd): Bind:int main( ) {int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9;( boost: : bind( &nine_arguments, _9, _2, _1, _6, _3, _8, _4, _5, _7) )( i1, i2 , i3, i4, i5, i6, i7, i8, i9) ;}4/18/2013
  • Library IX: Lambda#include <iostream>#include " boost/lambda/lambda. hpp“#include " boost/function. hpp“int main(){using namespace boost: : lambda;boost: : function< void(int, int, int) > f=std: : cout << _1 << "* "<< _2 << " +" << _3 << " =" <<_1*_2 +_3 << " n" ;f(1, 2, 3) ;f(3, 2, 1) ;}4/18/2013
  • Library X: FunctionUsage:#include <iostream>#include " boost/function. hpp“bool some_func(int i, double d){return i>d;}int main( ){boost: : function<bool ( int, double) > f;f=&some_func;}4/18/2013
  • Library XI: SignalsUsage:#include <iostream>#include " boost/signals. hpp“void my_first_slot( ) {std: : cout << " void my_first_slot() n" ;}class my_second_slot {public:void operator() () const {std: : cout << " void my_second_slot: : operator() ( ) constn";}};4/18/2013
  • Signals (contd)int main( ) {boost: : signal<void () > sig;sig. connect(&my_first_slot) ;sig. connect(my_second_slot() ) ;std: : cout << " Emitting a signal. . . n";sig() ;}4/18/2013
  • Library XII: Boost MPL(metaprogramming library)The Boost.MPL library is a general-purpose, high-level C++ templatemetaprogramming framework of compile-timealgorithms, sequences and metafunctions. Itprovides a conceptual foundation and anextensive set of powerful and coherent tools.Visit:http://www.boost.org/doc/libs/1_47_0/libs/mpl/doc/index.html4/18/2013
  • Library XIII: BGL (BoostGraph Library)Part of the Boost Graph Library is a generic interfacethat allows access to a graphs structure, but hidesthe details of the implementation. This is an “open”interface in the sense that any graph library thatimplements this interface will be interoperable withthe BGL generic algorithms and with other algorithmsthat also use this interface. The BGL provides somegeneral purpose graph classes that conform to thisinterface, but they are not meant to be the “only”graph classes; there certainly will be other graphclasses that are better for certain situations.Visit:http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/s4/18/2013
  • Section IV:Multithreading4/18/2013
  • C++ ThreadsStandard C++ contains no native support formultithreading, so it is not possible towrite portablemultithreaded code the same way you would writeportable code thatuses other standard library classeslike string, vector, list, and so on. The BoostThreadslibrary goes a long way toward making astandard, portable multithreading library though, andit is designed to minimize many commonmultithreadingheadaches.Visit:http://www.boost.org/doc/libs/1_47_0/doc/html/thread.html4/18/2013
  • ReferencesThinking in C++ (B. Eckel) Free online edition!Essential C++ (S. Lippman)Effective C++ (S. Meyers)C++ Programming Language (B. Stroustrup)Design Patterns(Gamma, Helm, Johnson,Vlissides)Object-Oriented Analysis and Design withApplications (G. Booch, et. al)4/18/2013
  • References (contd)http://www.cppreference.com/wiki/stl/vector/startGoogle C++ style guidelinehttp://google-styleguide.googlecode.com/svn/trunk/cppguide.xmlC++ FAQhttp://www.parashift.com/c++-faq-lite/index.html4/18/2013
  • Q & A