Top Banner
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Thu, 24 Jul 2014 11:54:01 UTC C++ All about C++
57
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: C++

PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information.PDF generated at: Thu, 24 Jul 2014 11:54:01 UTC

C++All about C++

Page 2: C++

ContentsArticles

C++ 1C++ Standard Library 13Standard Template Library 18C++ Technical Report 1 25Boost (C++ libraries) 32Const-correctness 34Virtual function 43Template (C++) 46

ReferencesArticle Sources and Contributors 52Image Sources, Licenses and Contributors 54

Article LicensesLicense 55

Page 3: C++

C++ 1

C++

C++

Paradigm(s) Multi-paradigm: procedural, functional, object-oriented, generic

Designed by Bjarne Stroustrup

Appeared in 1983

Stable release ISO/IEC 14882:2011 / 2011

Preview release C++14 / 2014

Typing discipline Static, Nominative

Major implementations LLVM Clang, GCC, Microsoft Visual C++, Intel C++ Compiler

Influenced by C, Simula, ALGOL 68, Ada, CLU, ML

Influenced Perl, LPC, Lua, Pike, Ada 95, Java, PHP, D, C99, C#, Falcon, Seed7

Implementation language C++

OS Cross-platform (multi-platform)

Filename extension(s) .cc .cpp .cxx .c++ .h .hh .hpp .hxx .h++

Website News, status & discussion about Standard C++ [1]

• C++ Programming at Wikibooks

C++ (pronounced cee plus plus) is a general purpose programming language. It has imperative, object-oriented andgeneric programming features, while also providing the facilities for low level memory manipulation.It is designed with a bias for systems programming (e.g. embedded systems, operating system kernels), withperformance, efficiency and flexibility of use as its design requirements. C++ has also been found useful in manyother contexts, including desktop applications, servers (e.g. e-commerce, web search, SQL), performance criticalapplications (e.g. telephone switches, space probes) and entertainment software, such as video games.It is a compiled language, with implementations of it available on many platforms. Various organizations providethem, including the FSF, LLVM, Microsoft and Intel.C++ is standardised by the International Organization for Standardization (ISO), which the latest (and current)having being ratified and published by ISO in September 2011 as ISO/IEC 14882:2011 (informally known asC++11). The C++ programming language was initially standardised in 1998 as ISO/IEC 14882:1998, which wasthen amended by the C++03, ISO/IEC 14882:2003, standard. The current standard (C++11) supersedes these, withnew features and an enlarged standard library.Before standardization (1989 onwards), C++ was developed by Bjarne Stroustrup at Bell Labs, starting in 1979, whowanted an efficient flexible language (like C) that also provided high level features for programme organization.Many other programming languages have been influenced by C++, including C#, Java, and newer versions of C(after 1998).

Page 4: C++

C++ 2

History

Bjarne Stroustrup, creator of C++

Bjarne Stroustrup, a Danish and British trained computer scientist,began his work on C++'s predecessor "C with Classes" in 1979. Themotivation for creating a new language originated from Stroustrup'sexperience in programming for his Ph.D. thesis. Stroustrup found thatSimula had features that were very helpful for large softwaredevelopment, but the language was too slow for practical use, whileBCPL was fast but too low-level to be suitable for large softwaredevelopment. When Stroustrup started working in AT&T Bell Labs, hehad the problem of analyzing the UNIX kernel with respect todistributed computing. Remembering his Ph.D. experience, Stroustrupset out to enhance the C language with Simula-like features. C was

chosen because it was general-purpose, fast, portable and widely used. As well as C and Simula's influences, otherlanguages also influenced C++, including, ALGOL 68, Ada, CLU and ML.

Initially, the class, derived class, strong typing, inlining, and default argument features were added to C viaStroustrup's "C with Classes" to C compiler, Cpre.[2]

In 1983, it was renamed from C with Classes to C++ (++ being the increment operator in C). New features wereadded including virtual functions, function name and operator overloading, references, constants, type-safe free-storememory allocation (new/delete), improved type checking, and BCPL style single-line comments with two forwardslashes (//), as well as the development of a proper compiler for C++, Cfront.In 1985, the first edition of The C++ Programming Language was released, which became the definitive referencefor the language, as there was not yet an official standard. The first commercial implementation of C++ was releasedin October of the same year.In 1989 C++ 2.0 was released followed by the updated second edition of The C++ Programming Language in 1991.New features in 2.0 included multiple inheritance, abstract classes, static member functions, const member functions,and protected members. In 1990, The Annotated C++ Reference Manual was published. This work became the basisfor the future standard. Late feature additions included templates, exceptions, namespaces, new casts, and a booleantype.In 2011, C++11 was released which added more features and enlarged the standard library further (compared to it in1998), providing more facilities for C++ programmers to use, with more additions planned for 2014 and 2017.

EtymologyAccording to Stroustrup: "the name signifies the evolutionary nature of the changes from C". This name is creditedto Rick Mascitti (mid-1983)[3] and was first used in December 1983.When Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in atongue-in-cheek spirit. The name stems from C's "++" operator (which increments the value of a variable) and acommon naming convention of using "+" to indicate an enhanced computer program. A joke goes that the nameitself has a bug: due to the use of post-increment, which increments the value of the variable but evaluates to theunincremented value, so C++ is no better than C, and the pre-increment ++C form should have been used instead, sothat C++ is better than C.During C++'s development period, the language had been referred to as "new C", then "C with Classes", beforeacquiring its final name.

Page 5: C++

C++ 3

PhilosophyThroughout C++'s life, its development and evolution has been informally governed by a set of rules that itsevolution should follow:•• It must be driven by actual problems and its features should be useful immediately in real world programmes.•• Every feature should be implementable (with a reasonably obvious way to do so).•• Programmers should be free to pick their own programming style, and that style should be fully supported by

C++.•• Allowing a useful feature is more important than preventing every possible misuse of C++.•• It should provide facilities for organising programmes into well defined separate parts, and provide facilities for

combining separately developed parts.• No implicit violations of the type system (but allow explicit violations that have been explicitly asked for by the

programmer).•• Make user created types have equal support and performance to built in types.•• Any features that you do not use you do not pay for (e.g. in performance).• There should be no language beneath C++ (except assembly language).• C++ should work alongside other pre-existing programming languages, rather than being part of its own separate

and incompatible programming environment.•• If what the programmer wants to do is unknown, allow the programmer to specify (provide manual control).

Standardization

Year C++ Standard Informal name

1998 ISO/IEC 14882:1998 C++98

2003 ISO/IEC 14882:2003 C++03

2007 ISO/IEC TR 19768:2007 C++TR1

2011 ISO/IEC 14882:2011 C++11

2014 N3690 (working draft C++14) C++14

C++ is standardized by an ISO working group, JTC1/SC22/WG21. So far it has seen three versions of C++ releasedand is currently working on releasing C++1y.In 1998, it standardized C++ for the first time as ISO/IEC 14882:1998 (informally known as C++98). In 2003 it thenpublished a new version of the C++ standard, ISO/IEC 14882:2003, which fixed problems which had been identifiedin C++98.In 2005, a technical report, called the "Library Technical Report 1" (TR1), was released. While not an official part ofthe standard, it specified a number of extensions to the standard library, which were then included in the next versionof C++ (then C++0x).The latest major revision of the C++ standard, C++11 (formerly known as C++0x), was approved and released on the12 August 2011, as 14882:2011.A small extension to C++11, C++14 (also known as C++1y) featuring mainly bug fixes and small improvements isplanned for release in 2014. It holds similar aims as C++03 did to C++98.After C++1y, a major revision, informally known as C++17, is planned for 2017.

Page 6: C++

C++ 4

LanguageC++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world program that usesthe C++ Standard Library stream facility to write a message to standard output:

# include <iostream>

int main()

{

std::cout << "Hello, world!\n";

}

Within functions that define a non-void return type, failure to return a value before control reaches the end of thefunction results in undefined behaviour (compilers typically provide the means to issue a diagnostic in such acase).[4] The sole exception to this rule is the main function, which implicitly returns a value of zero.[5]

Operators and operator overloading

Operators that cannot be overloaded

Operator Symbol

Scope resolution operator ::

Conditional operator ?:

dot operator .

Member selection operator .*

"sizeof" operator sizeof

"typeid" operator typeid

C++ provides more than 35 operators, covering basic arithmetic, bit manipulation, indirection, comparisons, logicaloperations and others. Almost all operators can be overloaded for user-defined types, with a few notable exceptionssuch as member access (. and .*) as well as the conditional operator. The rich set of overloadable operators iscentral to using user created types in C++ as well and as easily as built in types (so that the user using them cannottell the difference). The overloadable operators are also an essential part of many advanced C++ programmingtechniques, such as smart pointers. Overloading an operator does not change the precedence of calculationsinvolving the operator, nor does it change the number of operands that the operator uses (any operand may howeverbe ignored by the operator, though it will be evaluated prior to execution). Overloaded "&&" and "||" operators losetheir short-circuit evaluation property.

Object storageC++ supports four types of memory management:[6]

•• Static storage duration objects•• Thread storage duration objects•• Automatic storage duration objects•• Dynamic storage duration objects

Page 7: C++

C++ 5

Static storage duration objects

Static storage duration objects are created before main() (see exceptions below) is entered and destroyed in reverseorder of creation after main() exits. The exact order of creation is not specified by the standard (though there aresome rules defined below) to allow implementations some freedom in how to organize there implementation. Moreformally, objects of this type have a lifespan that "shall last for the duration of the program".[7]

Static storage duration objects are initialized in two phases. First, "static initialization" is performed, and only afterall static initialization is performed, "dynamic initialization" is performed:• Static initialization – all objects are first zero initialized. Then all objects that have an constant initialization phase

are initialized with the constant expression (ie variables initialized with a literal or `constexpr`). Though it is notspecified in the standard this phase can be completed at compile time and saved in the data partition of theexecutable.

• Dynamic initialization – all object initialization that is done via a constructor or function call (unless the functionis marked constexpr C++11). The dynamic initialization order is defined as the order of declaration within thecompilation unit (ie the same file). No guarantees about the order of initialization between compilation units isprovided.

Static members of a class. These are no different from file scope static variables in terms of lifespan (The majordifference is there viability).

Thread storage duration objects

Variables of this type are very similar to Static Storage duration objects. The main difference is the creation time isjust prior to thread creation and destruction is done after the thread has been joined.[8]

Automatic storage duration objects

These are the most common type of variable in C++:[9]

•• local variables inside a function/block.•• temporary variables.The common feature about automatic variables is that they have a lifespan that is limited to the scope of the variable.They are created and potentially initialized at the point of declaration (see below for details) and destroyed in thereverse order of creation when the scope is left.Local variables are created as the point of execution passes there declaration point. If the variable has a constructoror initializer this is used to define the initial state of the object. Local variables are destroyed when the local block orfunction that they are declared in is closed.Member variables are created when the parent object is created. Array members are initialized from 0 to the lastmember of the array in order. Member variables are destroyed when the parent object is destroyed in the reverseorder of creation. i.e. If the parent is an "automatic object" then it will be destroyed when it goes out of scope whichtriggers the destruction of all its members.Temporary variables are created as the result of expression evaluation and are destroyed when the statementcontaining the expression has been fully evaluated (usually at the ';' at the end of the statement).

Page 8: C++

C++ 6

Dynamic storage duration objects

These objects have a dynamic lifespan and are created with new call and destroyed with an explicit call to delete.[10]

TemplatesSee also: Template metaprogramming and Generic programmingC++ templates enable generic programming. C++ supports both function and class templates. Templates may beparameterized by types, compile-time constants, and other templates. Templates are implemented by instantiation atcompile-time. To instantiate a template, compilers substitute specific arguments for a template's parameters togenerate a concrete function or class instance. Some substitutions are not possible; these are eliminated by anoverload resolution policy described by the phrase "Substitution failure is not an error" (SFINAE). Templates are apowerful tool that can be used for generic programming, template metaprogramming, and code optimization, but thispower implies a cost. Template use may increase code size, because each template instantiation produces a copy ofthe template code: one for each set of template arguments, however, this is the same amount of code that would begenerated, or less, that if the code was written by hand. This is in contrast to run-time generics seen in otherlanguages (e.g., Java) where at compile-time the type is erased and a single template body is preserved.Templates are different from macros: while both of these compile-time language features enable conditionalcompilation, templates are not restricted to lexical substitution. Templates are aware of the semantics and typesystem of their companion language, as well as all compile-time type definitions, and can perform high-leveloperations including programmatic flow control based on evaluation of strictly type-checked parameters. Macros arecapable of conditional control over compilation based on predetermined criteria, but cannot instantiate new types,recurse, or perform type evaluation and in effect are limited to pre-compilation text-substitution andtext-inclusion/exclusion. In other words, macros can control compilation flow based on pre-defined symbols butcannot, unlike templates, independently instantiate new symbols. Templates are a tool for static polymorphism (seebelow) and generic programming.In addition, templates are a compile time mechanism in C++ that is Turing-complete, meaning that any computationexpressible by a computer program can be computed, in some form, by a template metaprogram prior to runtime.In summary, a template is a compile-time parameterized function or class written without knowledge of the specificarguments used to instantiate it. After instantiation, the resulting code is equivalent to code written specifically forthe passed arguments. In this manner, templates provide a way to decouple generic, broadly applicable aspects offunctions and classes (encoded in templates) from specific aspects (encoded in template parameters) withoutsacrificing performance due to abstraction.

ObjectsMain article: C++ classesC++ introduces object-oriented programming (OOP) features to C. It offers classes, which provide the four featurescommonly present in OOP (and some non-OOP) languages: abstraction, encapsulation, inheritance, andpolymorphism. One distinguishing feature of C++ classes compared to classes in other programming languages issupport for deterministic destructors, which in turn provide support for the Resource Acquisition is Initialization(RAII) concept.

Page 9: C++

C++ 7

Encapsulation

Encapsulation is the hiding of information to ensure that data structures and operators are used as intended and tomake the usage model more obvious to the developer. C++ provides the ability to define classes and functions as itsprimary encapsulation mechanisms. Within a class, members can be declared as either public, protected, or private toexplicitly enforce encapsulation. A public member of the class is accessible to any function. A private member isaccessible only to functions that are members of that class and to functions and classes explicitly granted accesspermission by the class ("friends"). A protected member is accessible to members of classes that inherit from theclass in addition to the class itself and any friends.The OO principle is that all of the functions (and only the functions) that access the internal representation of a typeshould be encapsulated within the type definition. C++ supports this (via member functions and friend functions),but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and isallowed to make public entities that are not part of the representation of the type. Therefore, C++ supports not justOO programming, but other weaker decomposition paradigms, like modular programming.It is generally considered good practice to make all data private or protected, and to make public only those functionsthat are part of a minimal interface for users of the class. This can hide the details of data implementation, allowingthe designer to later fundamentally change the implementation without changing the interface in any way.

Inheritance

Inheritance allows one data type to acquire properties of other data types. Inheritance from a base class may bedeclared as public, protected, or private. This access specifier determines whether unrelated and derived classes canaccess the inherited public and protected members of the base class. Only public inheritance corresponds to what isusually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted,a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is calledvirtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph,avoiding some of the ambiguity problems of multiple inheritance.Multiple inheritance is a C++ feature not found in most other languages, allowing a class to be derived from morethan one base class; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class caninherit from both "Cat" and "Flying Mammal". Some other languages, such as C# or Java, accomplish somethingsimilar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of baseclasses to one (interfaces, unlike classes, provide only declarations of member functions, no implementation ormember data). An interface as in C# and Java can be defined in C++ as a class containing only pure virtual functions,often known as an abstract base class or "ABC". The member functions of such an abstract base class are normallyexplicitly defined in the derived class, not inherited implicitly. C++ virtual inheritance exhibits an ambiguityresolution feature called dominance.

PolymorphismSee also: Polymorphism in object-oriented programmingPolymorphism enables one common interface for many implementations, and for objects to act differently underdifferent circumstances.C++ supports several kinds of static (compile-time) and dynamic (run-time) polymorphisms. Compile-timepolymorphism does not allow for certain run-time decisions, while run-time polymorphism typically incurs aperformance penalty.

Page 10: C++

C++ 8

Static polymorphism

Function overloading allows programs to declare multiple functions having the same name (but with differentarguments). The functions are distinguished by the number or types of their formal parameters. Thus, the samefunction name can refer to different functions depending on the context in which it is used. The type returned by thefunction is not used to distinguish overloaded functions and would result in a compile-time error message.When declaring a function, a programmer can specify for one or more parameters a default value. Doing so allowsthe parameters with defaults to optionally be omitted when the function is called, in which case the defaultarguments will be used. When a function is called with fewer arguments than there are declared parameters, explicitarguments are matched to parameters in left-to-right order, with any unmatched parameters at the end of theparameter list being assigned their default arguments. In many cases, specifying default arguments in a singlefunction declaration is preferable to providing overloaded function definitions with different numbers of parameters.Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code. In particular, throughthe Curiously Recurring Template Pattern, it's possible to implement a form of static polymorphism that closelymimics the syntax for overriding virtual functions. Because C++ templates are type-aware and Turing-complete, theycan also be used to let the compiler resolve recursive conditionals and generate substantial programs throughtemplate metaprogramming. Contrary to some opinion, template code will not generate a bulk code after compilationwith the proper compiler settings.

Dynamic polymorphism

Inheritance

Variable pointers (and references) to a base class type in C++ can refer to objects of any derived classes of that typein addition to objects exactly matching the variable type. This allows arrays and other kinds of containers to holdpointers to objects of differing types. Because assignment of values to variables usually occurs at run-time, this isnecessarily a run-time phenomenon.C++ also provides a dynamic_cast operator, which allows the program to safely attempt conversion of an objectinto an object of a more specific object type (as opposed to conversion to a more general type, which is alwaysallowed). This feature relies on run-time type information (RTTI). Objects known to be of a certain specific type canalso be cast to that type with static_cast, a purely compile-time construct that has no runtime overhead anddoes not require RTTI.

Virtual member functions

Ordinarily, when a function in a derived class overrides a function in a base class, the function to call is determinedby the type of the object. A given function is overridden when there exists no difference in the number or type ofparameters between two or more definitions of that function. Hence, at compile time, it may not be possible todetermine the type of the object and therefore the correct function to call, given only a base class pointer; thedecision is therefore put off until runtime. This is called dynamic dispatch. Virtual member functions or methodsallow the most specific implementation of the function to be called, according to the actual run-time type of theobject. In C++ implementations, this is commonly done using virtual function tables. If the object type is known, thismay be bypassed by prepending a fully qualified class name before the function call, but in general calls to virtualfunctions are resolved at run time.In addition to standard member functions, operator overloads and destructors can be virtual. A general rule of thumbis that if any functions in the class are virtual, the destructor should be as well. As the type of an object at its creationis known at compile time, constructors, and by extension copy constructors, cannot be virtual. Nonetheless asituation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as apointer to a base object. In such a case, a common solution is to create a clone() (or similar) virtual function thatcreates and returns a copy of the derived class when called.

Page 11: C++

C++ 9

A member function can also be made "pure virtual" by appending it with = 0 after the closing parenthesis andbefore the semicolon. A class containing a pure virtual function is called an abstract data type. Objects cannot becreated from abstract data types; they can only be derived from. Any derived class inherits the virtual function aspure and must provide a non-pure definition of it (and all other pure virtual functions) before objects of the derivedclass can be created. A program that attempts to create an object of a class with a pure virtual member function orinherited pure virtual member function is ill-formed.

Exception handlingException handling is a mechanism in C++ that is used to handle errors in a uniform manner and separately from themain body of a programme's source code. Should an error occur, an exception is thrown (raised), which is thencaught by an exception handler. The code that might cause an exception to be thrown goes in a try block (isenclosed in try { and }) and the exceptions are handled in separate catch blocks.

#include<iostream>

#include<vector>

int main()

try {

std::vector<int> vec{3,4,3,1};

int i{vec.at(4)};

}

//An exception handler, catches std::out_of_range

catch(std::out_of_range& e) {

std::cerr<<"Accessing a non-existent element: "<<e.what()<<'\n';

}

catch(std::exception& e) {

std::cerr<<"Exception thrown: "<<e.what()<<'\n';

}

Unknown exceptions from unknown errors can be caught by the handlers using catch(...) to catch allexceptions. As all the standard library exceptions have std::exception as their base class, catchingstd::exception will catch all standard library exceptions. As is shown above (e.what()), all exceptions thatderive from std::exception have a what() function that provides information about what caused the error -std::out_of_range is a descendent of std::exception.

Standard libraryThe C++ standard consists of two parts: the core language and the C++ Standard Library; which C++ programmersexpect on every major implementation of C++, it includes vectors, lists, maps, algorithms (find, for_each,binary_search, random_shuffle, etc.), sets, queues, stacks, arrays, tuples, input/output facilities (iostream; readingfrom the console input, reading/writing from files), smart pointers for automatic memory management, regularexpression support, multi-threading library, atomics support (allowing a variable to be read or written to be at mostone thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), asystem for converting error reporting that doesn't use C++ exceptions into C++ exceptions, a random numbergenerator and a slightly modified version of the C standard library (to make it comply with the C++ type system).A large part of the C++ library is based on the STL. This provides useful tools as containers (for example vectors and lists), iterators to provide these containers with array-like access and algorithms to perform operations such as searching and sorting. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export

Page 12: C++

C++ 10

compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with anycontainer or on any sequence defined by iterators. As in C, the features of the library are accessed by using the#include directive to include a standard header. C++ provides 105 standard headers, of which 27 are deprecated.The standard incorporates the STL was originally designed by Alexander Stepanov, who experimented with genericalgorithms and containers for many years. When he started with C++, he finally found a language where it waspossible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standardlibrary qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. Thestandard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used todistinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the Clibrary subset, etc.).Most C++ compilers, and all major ones, provide a standards conforming implementation of the C++ standardlibrary.

CompatibilityProducing a reasonably standards-compliant C++ compiler has proven to be a difficult task for compiler vendors ingeneral. For many years, different C++ compilers implemented the C++ language to different levels of compliance tothe standard, and their implementations varied widely in some areas such as partial template specialization. Recentreleases of most popular C++ compilers support almost all of the C++ 1998 standard.To give compiler vendors greater freedom, the C++ standards committee decided not to dictate the implementationof name mangling, exception handling, and other implementation-specific features. The downside of this decision isthat object code produced by different compilers is expected to be incompatible. There were, however, attempts tostandardize compilers for particular machines or operating systems (for example C++ ABI), though they seem to belargely abandoned now.

With CFor more details on this topic, see Compatibility of C and C++.C++ is often considered to be a superset of C, but this is not strictly true. Most C code can easily be made to compilecorrectly in C++, but there are a few differences that cause some valid C code to be invalid or behave differently inC++. For example, C allows implicit conversion from void* to other pointer types, but C++ does not (for typesafety reasons). Also, C++ defines many new keywords, such as new and class, which may be used as identifiers(for example, variable names) in a C program.Some incompatibilities have been removed by the 1999 revision of the C standard (C99), which now supports C++features such as line comments (//), and declarations mixed with code. On the other hand, C99 introduced a numberof new features that C++ did not support, were incompatible or redundant in C++, such as variable-length arrays,native complex-number types (use std::complex class that is, and was also there before C99 existed, in the C++standard library), designated initializers (use constructors instead), compound literals, the boolean typedef (in C++ itis a fundamental type) and the restrict keyword. Some of the C99-introduced features were included in thesubsequent version of the C++ standard, C++11 (out of those which were not redundant).To intermix C and C++ code, any function declaration or definition that is to be called from/used both in C and C++must be declared with C linkage by placing it within an extern "C" {/*...*/} block. Such a function maynot rely on features depending on name mangling (i.e., function overloading).

Page 13: C++

C++ 11

References[1] http:/ / isocpp. org/[2][2] Bjarne Stroustrup - HOPL-II paper[3] Bjarne Stroustrup - HOPL-II paper (http:/ / www. stroustrup. com/ hopl2. pdf)[4] ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages – C++ §6.6.3 The return statement [stmt.return] para. 2[5] ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages – C++ §3.6.1 Main function [basic.start.main] para. 5[6] ISO/IEC. Programming Languages – C++11 Draft (n3797) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2013/ n3797. pdf)

§3.7 Storage duration [basic.stc][7] ISO/IEC. Programming Languages – C++11 Draft (n3797) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2013/ n3797. pdf)

§3.7.1 Static Storage duration [basic.stc.static][8] ISO/IEC. Programming Languages – C++11 Draft (n3797) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2013/ n3797. pdf)

§3.7.2 Thread Storage duration [basic.stc.thread][9] ISO/IEC. Programming Languages – C++11 Draft (n3797) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2013/ n3797. pdf)

§3.7.3 Automatic Storage duration [basic.stc.auto][10] ISO/IEC. Programming Languages – C++11 Draft (n3797) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2013/ n3797. pdf)

§3.7.4 Dynamic Storage duration basic.stc.dynamic

Further reading• Abrahams, David; Gurtovoy, Aleksey. C++ Template Metaprogramming: Concepts, Tools, and Techniques from

Boost and Beyond. Addison-Wesley. ISBN 0-321-22725-5.• Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied.

Addison-Wesley. ISBN 0-201-70431-5.• Alexandrescu, Andrei; Sutter, Herb (2004). C++ Design and Coding Standards: Rules and Guidelines for

Writing Programs. Addison-Wesley. ISBN 0-321-11358-6.• Becker, Pete (2006). The C++ Standard Library Extensions : A Tutorial and Reference. Addison-Wesley.

ISBN 0-321-41299-0.• Brokken, Frank (2010). C++ Annotations (http:/ / www. icce. rug. nl/ documents/ cplusplus/ ). University of

Groningen. ISBN 90-367-0470-7.• Coplien, James O. (1992, reprinted with corrections 1994). Advanced C++: Programming Styles and Idioms.

ISBN 0-201-54855-0.• Dewhurst, Stephen C. (2005). C++ Common Knowledge: Essential Intermediate Programming. Addison-Wesley.

ISBN 0-321-32192-8.• Information Technology Industry Council (15 October 2003). Programming languages – C++ (Second ed.).

Geneva: ISO/IEC. 14882:2003(E).• Josuttis, Nicolai M. (2012). The C++ Standard Library, A Tutorial and Reference (Second ed.). Addison-Wesley.

ISBN 0-321-62321-5.• Koenig, Andrew; Moo, Barbara E. (2000). Accelerated C++ – Practical Programming by Example.

Addison-Wesley. ISBN 0-201-70353-X.• Lippman, Stanley B.; Lajoie, Josée; Moo, Barbara E. (2011). C++ Primer (Fifth ed.). Addison-Wesley.

ISBN 0-470-93244-9.• Lippman, Stanley B. (1996). Inside the C++ Object Model. Addison-Wesley. ISBN 0-201-83454-5.• Meyers, Scott (2005). Effective C++ (Third ed.). Addison-Wesley. ISBN 0-321-33487-6.• Stroustrup, Bjarne (2000). The C++ Programming Language (Special ed.). Addison-Wesley.

ISBN 0-201-70073-5.• Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley. ISBN 0-201-54330-3.

Page 14: C++

C++ 12

• Stroustrup, Bjarne (2009). Programming Principles and Practice Using C++. Addison-Wesley.ISBN 0-321-54372-6.

• Sutter, Herb (2001). More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, andSolutions. Addison-Wesley. ISBN 0-201-70434-X.

• Sutter, Herb (2004). Exceptional C++ Style. Addison-Wesley. ISBN 0-201-76042-8.• Vandevoorde, David; Josuttis, Nicolai M. (2003). C++ Templates: The complete Guide. Addison-Wesley.

ISBN 0-201-73484-2.

External links

Wikibooks has a book on the topic of: More C++ Idioms

• JTC1/SC22/WG21 (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ ) – The ISO/IEC C++ Standard WorkingGroup• n3242.pdf (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2011/ n3242. pdf) – Last publicly

available Committee Draft of "ISO/IEC IS 14882 – Programming Languages – C++" (28 February 2011)• n3337.pdf (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2012/ n3337. pdf) - First draft after the

C++11 standard, contains the C++11 standard plus minor editorial changes.• A paper by Stroustrup showing the timeline of C++ evolution (1991–2006) (http:/ / www. stroustrup. com/

hopl-almost-final. pdf)• Bjarne Stroustrup's C++ Style and Technique FAQ (http:/ / www. stroustrup. com/ bs_faq2. html)• C++ FAQ Lite by Marshall Cline (http:/ / www. parashift. com/ c+ + -faq-lite/ )• Hamilton, Naomi (25 June 2008). "The A-Z of Programming Languages: C++" (http:/ / www. computerworld.

com. au/ article/ 250514/ -z_programming_languages_c?pp=1& fp=16& fpid=1). Computerworld. Interview withBjarne Stroustrup.

• Kalev, Danny (15 August 2008). "The State of the Language: An Interview with Bjarne Stroustrup" (http:/ /www. devx. com/ SpecialReports/ Article/ 38813). DevX (QuinStreet Inc.).

• Katdare, Kaustubh (1 February 2008). "Dr. Bjarne Stroustrup – Inventor of C++" (http:/ / www. crazyengineers.com/ threads/ dr-bjarne-stroustrup-inventor-of-c. 62739/ ). CrazyEngineers.

• Code practices for not breaking binary compatibility between releases of C++ libraries (http:/ / techbase. kde. org/Policies/ Binary_Compatibility_Issues_With_C+ + ) (from KDE Techbase)

• The Standard C++ Foundation (http:/ / isocpp. org/ ) is a non-profit organization that promotes the use andunderstanding of standard C++. Bjarne Stroustrup is a director of the organization.

Page 15: C++

C++ Standard Library 13

C++ Standard LibraryIn the C++ programming language, the C++ Standard Library is a collection of classes and functions, which arewritten in the core language and part of the C++ ISO Standard itself.[1] The C++ Standard Library provides severalgeneric containers, functions to utilize and manipulate these containers, function objects, generic strings and streams(including interactive and file I/O), support for some language features, and everyday functions for tasks such asfinding the square root of a number. The C++ Standard Library also incorporates 18 headers of the ISO C90 Cstandard library ending with ".h", but their use is deprecated.[2] No other headers in the C++ Standard Library end in".h". Features of the C++ Standard Library are declared within the std namespace.The C++ Standard Library is based upon conventions introduced by the Standard Template Library (STL), and hasbeen influenced by research in generic programming and developers of the STL such as Alexander Stepanov andMeng Lee. Although the C++ Standard Library and the STL share many features, neither is a strict superset of theother.A noteworthy feature of the C++ Standard Library is that it not only specifies the syntax and semantics of genericalgorithms, but also places requirements on their performance.[3] These performance requirements often correspondto a well-known algorithm, which is expected but not required to be used. In most cases this requires linear timeO(n) or linearithmic time O(n log n), but in some cases higher bounds are allowed, such as quasilinear time O(n log2

n) for stable sort (to allow in-place merge sort). Previously sorting was only required to take O(n log n) on average,allowing the use of quicksort, which is fast in practice but has poor worst-case performance, but introsort wasintroduced to allow both fast average performance and optimal worst-case complexity, and as of C++11, sorting isguaranteed to be at worst linearithmic. In other cases requirements remain laxer, such as selection, which is onlyrequired to be linear on average (as in quicksort),[4] not requiring worst-case linear as in introselect.The C++ Standard Library underwent ISO standardization as part of the C++ ISO Standardization effort, and isundergoing further work regarding standardization of expanded functionality.

C++ StandardLibrary

•• Input/output•• Strings

Standard Template Library

•• algorithm

•• functional

•• iterator

•• Sequence containers•• Associative containers•• Unordered associative containers

C standard library

Page 16: C++

C++ Standard Library 14

•• Data types•• Character classification•• Strings•• Mathematics•• File input/output•• Date/time•• Localization•• Memory allocation•• Process control•• Signals•• Alternative tokens

Miscellaneous headers:• <assert.h>

• <errno.h>

• <setjmp.h>

• <stdarg.h>

•• v•• t• e [5]

Standard headersThe following files contain the declarations of the C++ Standard Library.

Containers<array>

New in C++11 and TR1. Provides the container class template std::array, a container for a fixed sizedarray.

<bitset>Provides the specialized container class std::bitset, a bit array.

<deque>Provides the container class template std::deque, a double-ended queue.

<forward_list>New in C++11 and TR1. Provides the container class template std::forward_list, a singly linked list.

<list>Provides the container class template std::list, a doubly linked list.

<map>Provides the container class templates std::map and std::multimap, sorted associative array andmultimap.

<queue>Provides the container adapter class std::queue, a single-ended queue, and std::priority_queue, apriority queue.

<set>Provides the container class templates std::set and std::multiset, sorted associative containers orsets.

<stack>

Page 17: C++

C++ Standard Library 15

Provides the container adapter class std::stack, a stack.<unordered_map>

New in C++11 and TR1. Provides the container class template std::unordered_map andstd::unordered_multimap, hash tables.

<unordered_set>New in C++11 and TR1. Provides the container class template std::unordered_set andstd::unordered_multiset.

<vector>Provides the container class template std::vector, a dynamic array.

General<algorithm>

Provides definitions of many container algorithms.<chrono>

Provides time elements, such as std::chrono::duration, std::chrono::time_point, andclocks.

<functional>Provides several function objects, designed for use with the standard algorithms.

<iterator>Provides classes and templates for working with iterators.

<memory>Provides facilities for memory management in C++, including the class template std::unique_ptr.

<stdexcept>Contains standard exception classes such as std::logic_error and std::runtime_error, bothderived from std::exception.

<tuple>New in C++11 and TR1. Provides a class template std::tuple, a tuple.

<utility>Provides the template class std::pair, for working with object pairs (two-member tuples), and thenamespace std::rel_ops, for easier operator overloading.

Localization<locale>

Defines classes and declares functions that encapsulate and manipulate the information peculiar to a locale.<codecvt>

Provides code conversion facets for various character encodings.

Strings<string>

Provides the C++ standard string classes and templates.<regex>

Page 18: C++

C++ Standard Library 16

New in C++11. Provides utilities for pattern matching strings using regular expressions.

Streams and Input/Output<fstream>

Provides facilities for file-based input and output. See fstream.<iomanip>

Provides facilities to manipulate output formatting, such as the base used when formatting integers and theprecision of floating point values.

<ios>Provides several types and functions basic to the operation of iostreams.

<iosfwd>Provides forward declarations of several I/O-related class templates.

<iostream>Provides C++ input and output fundamentals. See iostream.

<istream>Provides the template class std::istream and other supporting classes for input.

<ostream>Provides the template class std::ostream and other supporting classes for output.

<sstream>Provides the template class std::sstream and other supporting classes for string manipulation.

<streambuf>Provides reading and writing functionality to/from certain types of character sequences, such as external filesor strings.

Language support<exception>

Provides several types and functions related to exception handling, including std::exception, the baseclass of all exceptions thrown by the Standard Library.

<limits>Provides the template class std::numeric_limits, used for describing properties of fundamentalnumeric types.

<new>Provides operators new and delete and other functions and types composing the fundamentals of C++memory management.

<typeinfo>Provides facilities for working with C++ run-time type information.

Page 19: C++

C++ Standard Library 17

Thread support library<thread>

New in C++11. Provide class and namespace for working with threads.<mutex>

New in C++11. 30.4-1 This section provides mechanisms for mutual exclusion: mutexes, locks, and call once.<condition_variable>

New in C++11. 30.5-1 Condition variables provide synchronization primitives used to block a thread untilnotified by some other thread that some condition is met or until a system time is reached.

<future>New in C++11. 30.6.1-1 Describes components that a C++ program can use to retrieve in one thread the result(value or exception) from a function that has run in the same thread or another thread.

Numerics libraryComponents that C++ programs may use to perform seminumerical operations.<complex>

The header <complex> defines a class template, and numerous functions for representing and manipulatingcomplex numbers.

<random>Facility for generating (pseudo-)random numbers

<valarray>Defines five class templates (valarray, slice_array, gslice_array, mask_array, and indirect_array), two classes(slice and gslice), and a series of related function templates for representing and manipulating arrays of values.

<numeric>Generalized numeric operations.

C standard libraryMain article: C Standard LibraryEach header from the C Standard Library is included in the C++ Standard Library under a different name, generatedby removing the .h, and adding a 'c' at the start; for example, 'time.h' becomes 'ctime'. The only difference betweenthese headers and the traditional C Standard Library headers is that where possible the functions should be placedinto the std:: namespace. In ISO C, functions in the standard library are allowed to be implemented by macros, whichis not allowed by ISO C++.

Page 20: C++

C++ Standard Library 18

References[1] ISO/IEC 14882:2003(E) Programming Languages — C++ §17-27[2] ISO/IEC 14882:2003(E) Programming Languages — C++ §D.5[3] " Generic Algorithms (http:/ / www. cs. rpi. edu/ ~musser/ gp/ algorithms. html)", David Musser[4] nth_element (http:/ / en. cppreference. com/ w/ cpp/ algorithm/ nth_element)[5] http:/ / en. wikipedia. org/ w/ index. php?title=Template:C%2B%2B_Standard_Library& action=edit

• Bjarne Stroustrup: The C++ Programming Language, Addison-Wesley, ISBN 0-201-70073-5

External links• Standard C++ Library reference (http:/ / en. cppreference. com/ w/ cpp)• Microsoft MSDN Library - Standard C++ Library Reference (http:/ / msdn2. microsoft. com/ en-us/ library/

cscc687y(VS. 80). aspx)• SourcePro C++ Documentation (http:/ / www. roguewave. com/ support/ product-documentation/ sourcepro.

aspx)• STLport (http:/ / www. stlport. org/ )• The GNU Standard C++ Library (http:/ / gcc. gnu. org/ libstdc+ + )

Standard Template Library

C++ StandardLibrary

•• Input/output•• Strings

Standard Template Library

•• algorithm

•• functional

•• iterator

•• Sequence containers•• Associative containers•• Unordered associative containers

C standard library

•• Data types•• Character classification•• Strings•• Mathematics•• File input/output•• Date/time•• Localization•• Memory allocation•• Process control•• Signals•• Alternative tokens

Miscellaneous headers:• <assert.h>

• <errno.h>

• <setjmp.h>

• <stdarg.h>

Page 21: C++

Standard Template Library 19

•• v•• t• e [5]

The Standard Template Library (STL) is a software library for the C++ programming language that influencedmany parts of the C++ Standard Library. It provides four components called algorithms, containers, functional, anditerators.The STL provides a ready-made set of common classes for C++, such as containers and associative arrays, that canbe used with any built-in type and with any user-defined type that supports some elementary operations (such ascopying and assignment). STL algorithms are independent of containers, which significantly reduces the complexityof the library.The STL achieves its results through the use of templates. This approach provides compile-time polymorphism thatis often more efficient than traditional run-time polymorphism. Modern C++ compilers are tuned to minimize anyabstraction penalty arising from heavy use of the STL.The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind:generic programming, abstractness without loss of efficiency, the Von Neumann computation model, and valuesemantics.

Composition

ContainersThe STL contains sequence containers and associative containers. The standard sequence containers includevector , deque , and list . The standard associative containers are set , multiset , map , andmultimap . There are also container adaptorsqueue , priority_queue , and stack , that are containerswith specific interface, using other containers as implementation.

Container Description

Simple Containers

pair The pair container is a simple associative container consisting of a 2-tuple of data elements or objects, called 'first' and'second', in that fixed order. The STL 'pair' can be assigned, copied and compared. The array of objects allocated in a mapor hash_map (described below) are of type 'pair' by default, where all the 'first' elements act as the unique keys, eachassociated with their 'second' value objects.

Sequences (Arrays/Linked Lists): ordered collections

vector a dynamic array, like C array (i.e., capable of random access) with the ability to resize itself automatically when insertingor erasing an object. Inserting and removing an element to/from back of the vector at the end takes amortized constanttime. Inserting and erasing at the beginning or in the middle is linear in time. A specialization for type bool exists, whichoptimizes for space by storing bool values as bits.

list a doubly linked list; elements are not stored in contiguous memory. Opposite performance from a vector. Slow lookupand access (linear time), but once a position has been found, quick insertion and deletion (constant time).

deque (double-endedqueue)

a vector with insertion/erase at the beginning or end in amortized constant time, however lacking some guarantees oniterator validity after altering the deque.

Container adaptors

queue Provides FIFO queue interface in terms of push /pop /front /back operations. Any sequence supportingoperations front() , back() , push_back() , and pop_front() can be used to instantiatequeue (e.g. list and deque ).

Page 22: C++

Standard Template Library 20

priority queue Provides priority queue interface in terms of push/pop/top operations (the element with the highest priority ison top). Any random-access sequence supporting operations front() , push_back() , andpop_back() can be used to instantiate priority_queue (e.g. vector and deque ).Elements should additionally support comparison (to determine which element has a higher priority and should be poppedfirst).

stack Provides LIFO stack interface in terms of push/pop/top operations (the last-inserted element is on top). Anysequence supporting operations back() , push_back() , and pop_back() can be used to instantiatestack (e.g. vector , list , and deque ).

Associative containers: unordered collections

set a mathematical set; inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides setoperations union, intersection, difference, symmetric difference and test of inclusion. Type of data must implementcomparison operator < or custom comparator function must be specified; such comparison operator or comparatorfunction must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using aself-balancing binary search tree.

multiset same as a set, but allows duplicate elements (mathematical Multiset).

map an associative array; allows mapping from one data item (a key) to another (a value). Type of key must implementcomparison operator < or custom comparator function must be specified; such comparison operator or comparatorfunction must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using aself-balancing binary search tree.

multimap same as a map, but allows duplicate keys.

unordered_setunordered_multiset

unordered_mapunordered_multimap

similar to a set, multiset, map, or multimap, respectively, but implemented using a hash table; keys are not ordered, but ahash function must exist for the key type. These containers are part of C++11.

Other types of containers

bitset stores series of bits similar to a fixed-sized vector of bools. Implements bitwise operations and lacks iterators. Not aSequence.

valarray another C-like array like vector, but is designed for high speed numerics at the expense of some programming ease andgeneral purpose use. It has many features that make it ideally suited for use with vector processors in traditional vectorsupercomputers and SIMD units in consumer-level scalar processors, and also ease vector mathematics programmingeven in scalar computers.

IteratorsThe STL implements five different types of iterators. These are input iterators (that can only be used to read asequence of values), output iterators (that can only be used to write a sequence of values), forward iterators (that canbe read, written to, and move forward), bidirectional iterators (that are like forward iterators, but can also movebackwards) and random access iterators (that can move freely any number of steps in one operation).It is possible to have bidirectional iterators act like random access iterators, as moving forward ten steps could bedone by simply moving forward a step at a time a total of ten times. However, having distinct random accessiterators offers efficiency advantages. For example, a vector would have a random access iterator, but a list only abidirectional iterator.Iterators are the major feature that allow the generality of the STL. For example, an algorithm to reverse a sequencecan be implemented using bidirectional iterators, and then the same implementation can be used on lists, vectors anddeques. User-created containers only have to provide an iterator that implements one of the five standard iteratorinterfaces, and all the algorithms provided in the STL can be used on the container.This generality also comes at a price at times. For example, performing a search on an associative container such as a map or set can be much slower using iterators than by calling member functions offered by the container itself. This is because an associative container's methods can take advantage of knowledge of the internal structure, which is

Page 23: C++

Standard Template Library 21

opaque to algorithms using iterators.

AlgorithmsA large number of algorithms to perform operations such as searching and sorting are provided in the STL, eachimplemented to require a certain level of iterator (and therefore will work on any container that provides an interfaceby iterators).

FunctorsThe STL includes classes that overload the function call operator (operator() ). Instances of such classes arecalled functors or function objects. Functors allow the behavior of the associated function to be parameterized (e.g.through arguments passed to the functor's constructor) and can be used to keep associated per-functor stateinformation along with the function. Since both functors and function pointers can be invoked using the syntax of afunction call, they are interchangeable as arguments to templates when the corresponding parameter only appears infunction call contexts.A particularly common type of functor is the predicate. For example, algorithms like find_if take a unarypredicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sortedcontainers use a binary predicate that must provide a strict weak ordering, that is, it must behave like a membershiptest on a transitive, non reflexive and asymmetric binary relation. If none is supplied, these algorithms and containersuse less [1] by default, which in turn calls the less-than-operator <.

HistoryThe architecture of STL is largely the creation of Alexander Stepanov. In 1979 he began working out his initial ideasof generic programming and exploring their potential for revolutionizing software development. Although DavidMusser had developed and advocated some aspects of generic programming already by year 1971, it was limited to arather specialized area of software development (computer algebra).Stepanov recognized the full potential for generic programming and persuaded his then-colleagues at GeneralElectric Research and Development (including, primarily, David Musser and Deepak Kapur) that genericprogramming should be pursued as a comprehensive basis for software development. At the time there was no realsupport in any programming language for generic programming.The first major language to provide such support was Ada (ANSI standard 1983), with its generic units feature. In1985, the Eiffel programming language became the first object-oriented language to include intrinsic support forgeneric classes, combined with the object-oriented notion of inheritance.[2] By 1987 Stepanov and Musser haddeveloped and published an Ada library for list processing that embodied the results of much of their research ongeneric programming. However, Ada had not achieved much acceptance outside the defense industry and C++seemed more likely to become widely used and provide good support for generic programming even though thelanguage was relatively immature. Another reason for turning to C++, which Stepanov recognized early on, was theC/C++ model of computation that allows very flexible access to storage via pointers, which is crucial to achievinggenerality without losing efficiency.Much research and experimentation were needed, not just to develop individual components, but to develop anoverall architecture for a component library based on generic programming. First at AT&T Bell Laboratories andlater at Hewlett-Packard Research Labs (HP), Stepanov experimented with many architectural and algorithmformulations, first in C and later in C++. Musser collaborated in this research and in 1992 Meng Lee joinedStepanov's project at HP and became a major contributor.This work undoubtedly would have continued for some time being just a research project or at best would have resulted in an HP proprietary library, if Andrew Koenig of Bell Labs had not become aware of the work and asked

Page 24: C++

Standard Template Library 22

Stepanov to present the main ideas at a November 1993 meeting of the ANSI/ISO committee for C++standardization. The committee's response was overwhelmingly favorable and led to a request from Koenig for aformal proposal in time for the March 1994 meeting. Despite the tremendous time pressure, Alex and Meng wereable to produce a draft proposal that received preliminary approval at that meeting.The committee had several requests for changes and extensions (some of them major), and a small group ofcommittee members met with Stepanov and Lee to help work out the details. The requirements for the mostsignificant extension (associative containers) had to be shown to be consistent by fully implementing them, a taskStepanov delegated to Musser. Stepanov and Lee produced a proposal that received final approval at the July 1994ANSI/ISO committee meeting. (Additional details of this history can be found in Stevens.) Subsequently, theStepanov and Lee document 17 was incorporated into the ANSI/ISO C++ draft standard (1, parts of clauses 17through 27). It also influenced other parts of the C++ Standard Library, such as the string facilities, and some of thepreviously adopted standards in those areas were revised accordingly.In spite of STL's success with the committee, there remained the question of how STL would make its way intoactual availability and use. With the STL requirements part of the publicly available draft standard, compiler vendorsand independent software library vendors could of course develop their own implementations and market them asseparate products or as selling points for their other wares. One of the first edition's authors, Atul Saini, was amongthe first to recognize the commercial potential and began exploring it as a line of business for his company, ModenaSoftware Incorporated, even before STL had been fully accepted by the committee.The prospects for early widespread dissemination of STL were considerably improved with Hewlett-Packard'sdecision to make its implementation freely available on the Internet in August 1994. This implementation, developedby Stepanov, Lee, and Musser during the standardization process, became the basis of many implementations offeredby compiler and library vendors today.

Criticisms

Quality of implementation of C++ compilersThe Quality of Implementation (QoI) of the C++ compiler has a large impact on usability of STL (and templatedcode in general):• Error messages involving templates tend to be very long and difficult to decipher. This problem has been

considered so severe that a number of tools have been written that simplify and prettyprint STL-related errormessages to make them more comprehensible.

• Careless use of STL templates can lead to code bloat.Wikipedia:Citation needed This has been countered withspecial techniques within STL implementation (using void* containers internally) and by improving optimizationtechniques used by compilers. This is similar to carelessly just copying a whole set of C library functions to workwith a different type.

• Template instantiation tends to increase compilation time and memory usage (even by an order ofmagnitude)Wikipedia:Citation needed. Until the compiler technology improves enough, this problem can be onlypartially eliminated by very careful coding and avoiding certain idioms.

Page 25: C++

Standard Template Library 23

Other issues• Initialization of STL containers with constants within the source code is not as easy as data structures inherited

from C (addressed in C++11 with initializer lists).•• STL containers are not intended to be used as base classes (their destructors are deliberately non-virtual); deriving

from a container is a common mistake.• The concept of iterators as implemented by STL can be difficult to understand at first: for example, if a value

pointed to by the iterator is deleted, the iterator itself is then no longer valid. This is a common source of errors.Most implementations of the STL provide a debug mode that is slower, but can locate such errors if used. Asimilar problem exists in other languages, for example Java. Ranges have been proposed as a safer, more flexiblealternative to iterators.

• Certain iteration patterns do not map to the STL iterator model.Wikipedia:Citation needed For example, callbackenumeration APIs cannot be made to fit the STL model without the use of coroutines, which areplatform-dependent or unavailable, and are outside the C++ standard.

• Compiler compliance does not guarantee that Allocator objects, used for memory management for containers, willwork with state-dependent behavior. For example, a portable library can't define an allocator type that will pullmemory from different pools using different allocator objects of that type. (Meyers, p. 50) (addressed in C++11).

• The set of algorithms is not complete: for example, the copy_if algorithm was left out, though it has beenadded in C++11.[3]

• The interface of some containers (in particular string) is argued to be bloated (Sutter and Alexandrescu, p. 79);others are argued to be insufficient.

• Hashing containers were left out of the original standard (but added in Technical Report 1 for C++03), and havebeen added in C++11.

Implementations• Original STL implementation by Stepanov and Lee. 1994, Hewlett-Packard. No longer maintained.• SGI STL, based on original implementation by Stepanov & Lee. 1997, Silicon Graphics. No longer maintained.• libstdc++ by the GNU Project (was part of libg++)• libc++ from clang• STLPort, based on SGI STL• Rogue Wave Standard Library (HP, SGI, SunSoft, Siemens-Nixdorf)• Dinkum STL library by P.J. Plauger• The Microsoft STL [4] which ships with Visual C++ is a licensed derivative of Dinkum's STL.• Apache C++ Standard Library [5] (The starting point for this library was the 2005 version of the Rogue Wave

standard library[6])• EASTL [7], developed by Paul Pedriana at Electronic Arts and published as part of EA Open Source [8].

Page 26: C++

Standard Template Library 24

Notes[1] http:/ / www. sgi. com/ tech/ stl/ less. html[2] Meyer, Bertrand. Genericity versus inheritance, in ACM Conference on Object-Oriented Programming Languages Systems and Applications

(OOPSLA), Portland (Oregon), September 29 - October 2, 1986, pages 391-405.[3] More STL algorithms (revision 2) (http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2008/ n2666. pdf)[4] http:/ / msdn. microsoft. com/ en-us/ library/ c191tb28(v=vs. 80). aspx[5] http:/ / stdcxx. apache. org[6] Apache C++ Standard Library (http:/ / stdcxx. apache. org/ ). Stdcxx.apache.org. Retrieved on 2013-07-29.[7] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2007/ n2271. html[8] http:/ / gpl. ea. com/

References• Alexander Stepanov and Meng Lee, The Standard Template Library. HP Laboratories Technical Report

95-11(R.1), 14 November 1995. (Revised version of A. A. Stepanov and M. Lee: The Standard Template Library,Technical Report X3J16/94-0095, WG21/N0482, ISO Programming Language C++ Project, May 1994.) (http:/ /www. stepanovpapers. com)

• Alexander Stepanov (2007). Notes on Programming (http:/ / www. stepanovpapers. com/ notes. pdf) (PDF).Stepanov reflects about the design of the STL.

• Nicolai M. Josuttis (2000). The C++ Standard Library: A Tutorial and Reference. Addison-Wesley.ISBN 0-201-37926-0.

• Scott Meyers (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library.Addison-Wesley. ISBN 0-201-74962-9.

• Al Stevens (March 1995). "Al Stevens Interviews Alex Stepanov" (http:/ / www. sgi. com/ tech/ stl/drdobbs-interview. html). Dr. Dobb's Journal. Retrieved 18 July 2007.

• David Vandevoorde and Nicolai M. Josuttis (2002). C++ Templates: The Complete Guide. Addison-WesleyProfessional. ISBN 0-201-73484-2.

• Atul Saini and David R. Musser, STL Tutorial and Reference Guide: C+ + Programming with the StandardTemplate Library. Foreword by Alexander Stepanov; [Copyright Modena Software Inc.] Addison-Wesley ISBN0-201-63398-1

External links• C/C++ STL reference (http:/ / en. cppreference. com/ w/ cpp/ container), includes C++11 features• STL programmer's guide (http:/ / www. sgi. com/ tech/ stl/ ) guide from SGI• Apache (formerly Rogue Wave) C++ Standard Library Class Reference (http:/ / stdcxx. apache. org/ doc/

stdlibref/ index. html)• Apache (formerly Rogue Wave) C++ Standard Library User Guide (http:/ / stdcxx. apache. org/ doc/ stdlibug/

index. html)• Bjarne Stroustrup on The emergence of the STL (http:/ / www. stroustrup. com/ DnE2005. pdf) (Page 5, Section

3.1)

Page 27: C++

C++ Technical Report 1 25

C++ Technical Report 1C++ Technical Report 1 (TR1) is the common name for ISO/IEC TR 19768, C++ Library Extensions, which wasa document proposing additions to the C++ standard library for the C++03 language standard. The additions includeregular expressions, smart pointers, hash tables, and random number generators. TR1 was not a standard itself, butrather a draft document. However, most of its proposals became part of the current official standard, C++11. BeforeC++11 was standardized, vendors used this document as a guide to create extensions. The report's goal was "to buildmore widespread existing practice for an expanded C++ standard library."The report was first circulated in draft form in 2005 as Draft Technical Report on C++ Library Extensions [1], thenpublished in 2007 as an ISO/IEC standard as ISO/IEC TR 19768:2007 [2].

OverviewCompilers needed not include the TR1 components to be conforming to the C++ standard, because TR1 proposalswere not part of the standard itself, but only a set of possible additions that were still to be ratified. However, most ofit was available from Boost, and several compiler/library distributors implemented all or part of the components.TR1 was not a complete list of additions to the library that were going to appear in the next standard, C++11. Forexample, C++11 includes thread support library that is not available in TR1.The new components were defined in the std::tr1 namespace to distinguish them from the then current standardlibrary.There is also a second technical report, C++ Technical Report 2, planned for publishing after C++11 [3].

ComponentsTR1 includes the following components:

General utilitiesReference wrapper – enables passing references, rather than copies, into algorithms or function objects. The featurewas based on Boost.Ref.[4] A wrapper reference is obtained from an instance of the template classreference_wrapper. Wrapper references are similar to normal references (‘&’) of the C++ language. To obtaina wrapper reference from any object the template class ref is used (for a constant reference cref is used).Wrapper references are useful above all for template functions, when argument deduction would not deduce areference (e.g. when forwarding arguments):

#include <iostream>

#include <tr1/functional>

void f( int &r ) { ++r; }

template< class Funct, class Arg >

void g( Funct f, Arg t )

{

f(t);

}

int main()

{

Page 28: C++

C++ Technical Report 1 26

int i = 0;

g( f, i ); // 'g< void(int &r), int >' is instantiated

std::cout << i << "\n"; // Output: 0

g( f, std::tr1::ref(i) ); // 'g< void(int &r), reference_wrapper<int> >' is instanced

std::cout << i << "\n"; // Output: 1

}

Smart pointers – adds several classes that simplify object lifetime management in complex cases. Three mainclasses are added:• shared_ptr – a reference-counted smart pointer• weak_ptr – a variant of shared_ptr that doesn't increase the reference countThe proposal is based on Boost Smart Pointer library [5]

Function objectsThese four modules are added to the <functional> header file:Polymorphic function wrapper (function) – can store any callable function (function pointers, memberfunction pointers, and function objects) that uses a specified function call signature. The type does not depend on thekind of the callable used. Based on Boost.Function [6]

Function object binders (bind) – can bind any parameter parameters to function objects. Function composition isalso allowed. This is a generalized version of the standard std::bind1st and std::bind2nd bind functions.The feature is based on Boost Bind library.[7]

Function return types (result_of) – determines the type of a call expression.mem_fn – enhancement to the standard std::mem_fun and std::mem_fun_ref. Allows pointers to memberfunctions to be treated as function objects. Based on Boost Mem Fn library [8]

Metaprogramming and type traitsThere is now <type_traits> header file that contains many useful trait meta-templates, such as is_pod,has_virtual_destructor, remove_extent, etc. It facilitates metaprogramming by enabling queries onand transformation between different types The proposal is based on Boost Type Traits library [9].

Numerical facilities

Random number generation

• new <random> header file – variate_generator, mersenne_twister, poisson_distribution,etc.

• utilities for generating random numbers using any of several Pseudorandom number generators, engines, andprobability distributions

Page 29: C++

C++ Technical Report 1 27

Mathematical special functions

Some features of TR1, such as the mathematical special functions and certain C99 additions, are not includedin the Visual C++ implementation of TR1. The Mathematical special functions library was not standardized inC++11.• additions to the <cmath>/<math.h> header files – beta, legendre, etc.These functions will likely be of principal interest to programmers in the engineering and scientific disciplines.The following table shows all 23 special functions described in TR1.

Function name Functionprototype

Mathematical expression

AssociatedLaguerre

polynomials

doubleassoc_laguerre(unsigned n,unsigned m,double x ) ;

AssociatedLegendre

polynomials

doubleassoc_legendre(unsigned l,unsigned m,double x ) ;

Beta function double beta(double x, double y) ;

Complete ellipticintegral of the first

kind

doublecomp_ellint_1(double k ) ;

Complete ellipticintegral of thesecond kind

doublecomp_ellint_2(double k ) ;

Complete ellipticintegral of the

third kind

doublecomp_ellint_3(double k, doublenu ) ;

Confluenthypergeometric

functions

doubleconf_hyperg(double a, double c,double x ) ;

Regular modifiedcylindrical Bessel

functions

doublecyl_bessel_i(double nu, doublex ) ;

Cylindrical Besselfunctions of the

first kind

doublecyl_bessel_j(double nu, doublex ) ;

Irregular modifiedcylindrical Bessel

functions

doublecyl_bessel_k(double nu, doublex ) ;

Page 30: C++

C++ Technical Report 1 28

CylindricalNeumann functionsCylindrical Bessel

functions of thesecond kind

doublecyl_neumann(double nu, doublex ) ;

Incomplete ellipticintegral of the first

kind

double ellint_1(double k, doublephi ) ;

Incomplete ellipticintegral of thesecond kind

double ellint_2(double k, doublephi ) ;

Incomplete ellipticintegral of the

third kind

double ellint_3(double k, doublenu, double phi ) ;

Exponentialintegral

double expint(double x ) ;

Hermitepolynomials

double hermite(unsigned n, doublex ) ;

Hypergeometricseries

double hyperg(double a, double b,double c, double x) ;

Laguerrepolynomials

double laguerre(unsigned n, doublex ) ;

Legendrepolynomials

double legendre(unsigned l, doublex ) ;

Riemann zetafunction

doubleriemann_zeta(double x ) ;

Spherical Besselfunctions of the

first kind

doublesph_bessel(unsigned n, doublex ) ;

Sphericalassociated

Legendre functions

doublesph_legendre(unsigned l,unsigned m,double theta ) ;

SphericalNeumann functions

Spherical Besselfunctions of the

second kind

doublesph_neumann(unsigned n, doublex ) ;

Each function has two additional variants. Appending the suffix ‘f’ or ‘l’ to a function name gives a function thatoperates on float or long double values respectively. For example:

Page 31: C++

C++ Technical Report 1 29

float sph_neumannf( unsigned n, float x ) ;

long double sph_neumannl( unsigned n, long double x ) ;

Containers

Tuple types

• new <tuple> header file – tuple• based on Boost Tuple library [10]

• vaguely an extension of the standard std::pair• fixed size collection of elements, which may be of different types

Fixed size array

• new <array> header file – array• taken from Boost Array library [11]

• as opposed to dynamic array types such as the standard std::vector

Hash tables

• new <unordered_set>, <unordered_map> header files• they implement the unordered_set, unordered_multiset, unordered_map, andunordered_multimap classes, analogous to set, multiset, map, and multimap, respectively• unfortunately, unordered_set and unordered_multiset cannot be used with the set_union,set_intersection, set_difference, set_symmetric_difference, and includes standardlibrary functions, which work for set and multiset

•• new implementation, not derived from an existing library, not fully API compatible with existing libraries• like all hash tables, often provide constant time lookup of elements but the worst case can be linear in the size of

the container

Regular expressions• new <regex> header file – regex, regex_match, regex_search, regex_replace, etc.• based on Boost RegEx library [12]

•• pattern matching library

C compatibilityC++ is designed to be compatible with the C programming language, but is not a strict superset of C due to divergingstandards. TR1 attempts to reconcile some of these differences through additions to various headers in the C++library, such as <complex>, <locale>, <cmath>, etc. These changes help to bring C++ more in line with the C99version of the C standard (not all parts of C99 are included in TR1).

Page 32: C++

C++ Technical Report 1 30

Technical Report 2In 2005 a request for proposals for a TR2 was made with a special interest in Unicode, XML/HTML, Networkingand usability for novice programmers.[3].Some of the proposals included:• Threads [13]• The Asio C++ library (networking [14][15]).• Signals/Slots [16][17]• Filesystem Library [18] – Based on the Boost Filesystem Library, for query/manipulation of paths, files and

directories.• Boost Any Library [19]• Lexical Conversion Library [20]• New String Algorithms [21]• Toward a More Complete Taxonomy of Algebraic Properties for Numeric Libraries in TR2 [22]• Adding heterogeneous comparison lookup to associative containers for TR2 [23]Since the call for proposals for TR2 changes to ISO procedures meant that there will not be a TR2, insteadenhancements to C++ will be published in a number of Technical Specifications. Some of the proposals listed aboveare already included in the C++ standard or in draft versions of the Technical Specifications.

Notes[1] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1836. pdf[2] http:/ / www. iso. org/ iso/ iso_catalogue/ catalogue_ics/ catalogue_detail_ics. htm?ics1=35& ics2=60& ics3=& csnumber=43289[3] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1810. html[4] Chapter 22. Boost.Ref – Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ ref. html)[5] Smart Pointers – Boost 1.48.0 (http:/ / www. boost. org/ libs/ smart_ptr/ smart_ptr. htm)[6] Chapter 9. Boost.Function – Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ function. html)[7] Boost: bind.hpp documentation – Boost 1.48.0 (http:/ / www. boost. org/ libs/ bind/ bind. html)[8] Boost: mem_fn.hpp documentation – Boost 1.48.0 (http:/ / www. boost. org/ libs/ bind/ mem_fn. html)[9] http:/ / www. boost. org/ doc/ libs/ 1_37_0/ libs/ type_traits/ doc/ html/ index. html[10] The Boost Tuple Library – Boost 1.48.0 (http:/ / www. boost. org/ libs/ tuple/ doc/ tuple_users_guide. html)[11] Chapter 3. Boost.Array – Boost 1.48.0 (http:/ / www. boost. org/ doc/ html/ array. html)[12] Boost.Regex – Boost 1.36.0 (http:/ / www. boost. org/ doc/ libs/ 1_36_0/ libs/ regex/ doc/ html/ index. html)[13] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1883. pdf[14] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1925. pdf[15] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2007/ n2175. pdf[16] http:/ / www. mail-archive. com/ libsigc-list@gnome. org/ msg00115. html[17] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n2086. pdf[18] http:/ / www. open-std. org/ JTC1/ sc22/ WG21/ docs/ papers/ 2011/ n3239. html[19] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n1939. html[20] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n1973. html[21] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2006/ n2059. html#abstract[22] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2008/[23] http:/ / www. open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2009/ n2882. pdf

Page 33: C++

C++ Technical Report 1 31

References• ISO/IEC JTC1/SC22/WG21 (2005-06-24). Draft Technical Report on C++ Library Extensions (http:/ / www.

open-std. org/ jtc1/ sc22/ wg21/ docs/ papers/ 2005/ n1836. pdf) (PDF).• "ISO/IEC TR 19768:2007" (http:/ / www. iso. org/ iso/ iso_catalogue/ catalogue_ics/ catalogue_detail_ics.

htm?ics1=35& ics2=60& ics3=& csnumber=43289).• Becker, Peter (2006). The C++ Standard Library Extensions: A Tutorial and Reference. Addison-Wesley

Professional. ISBN 0-321-41299-0.

External links• Scott Meyers' Effective C++: TR1 Information (http:/ / aristeia. com/ EC3E/ TR1_info_frames. html) – contains

links to the TR1 proposal documents which provide background and rationale for the TR1 libraries.

Page 34: C++

Boost (C++ libraries) 32

Boost (C++ libraries)

Boost

Boost logo

Stable release 1.55.0 / November 11, 2013

Written in C++

Type Libraries

License Boost Software License

Website www.boost.org [1]

Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such aslinear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unittesting. It contains over eighty individual libraries.Most of the Boost libraries are licensed under the Boost Software License, designed to allow Boost to be used withboth free and proprietary software projects. Many of Boost's founders are on the C++ standards committee, andseveral Boost libraries have been accepted for incorporation into both Technical Report 1 and the C++11 standard.

DesignThe libraries are aimed at a wide range of C++ users and application domains. They range from general-purposelibraries like the smart pointer library, to operating system abstractions like Boost FileSystem, to libraries primarilyaimed at other library developers and advanced C++ users, like the template metaprogramming (MPL) anddomain-specific language (DSL) creation (Proto).In order to ensure efficiency and flexibility, Boost makes extensive use of templates. Boost has been a source ofextensive work and research into generic programming and metaprogramming in C++.Wikipedia:Citation neededMost Boost libraries are header based, consisting of inline functions and templates, and as such do not need to bebuilt in advance of their use. Some Boost libraries coexist as independent libraries.

Page 35: C++

Boost (C++ libraries) 33

Associated peopleOriginal founders of Boost still active in the community include Beman Dawes and David Abrahams. Author ofseveral books on C++, Nicolai Josuttis contributed the Boost array library in 2001. There are mailing lists devoted toBoost library use and library development, active as of 2014[2].

References[1] http:/ / www. boost. org/[2] http:/ / en. wikipedia. org/ w/ index. php?title=Boost_(C%2B%2B_libraries)& action=edit

Further reading• Demming, Robert & Duffy, Daniel J. (2010). Introduction to the Boost C++ Libraries. Volume 1 - Foundations.

Datasim. ISBN 978-94-91028-01-4.• Demming, Robert & Duffy, Daniel J. (2012). Introduction to the Boost C++ Libraries. Volume 2 - Advanced

Libraries. Datasim. ISBN 978-94-91028-02-1.• Karlsson, Björn (2005). Beyond the C++ Standard Library: An Introduction to Boost. Addison-Wesley.

ISBN 978-0-321-13354-0.• Polukhin, Antony (2013). Boost C++ Application Development Cookbook. Packt. ISBN 978-1-84951-488-0.• Schäling, Boris (2011). The Boost C++ Libraries. XML Press. ISBN 978-0-9822191-9-5.• Siek, Jeremy G.; Lee, Lie-Quan & Lumsdaine, Andrew (2001). The Boost Graph Library: User Guide and

Reference Manual. Addison-Wesley. ISBN 978-0-201-72914-6.

External links

The Wikibook C++ Programming has a page on the topic of: Libraries/Boost

• Official website (http:/ / www. boost. org/ )• "The Boost C++ Libraries" (http:/ / en. highscore. de/ cpp/ boost/ ): online book

Page 36: C++

Const-correctness 34

Const-correctnessIn computer programming, const-correctness is the form of program correctness that deals with the properdeclaration of variables or objects as mutable or immutable. The term is mostly used in a C or C++ context, andtakes its name from the const keyword in those languages.The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwritable. Rather,const-ness is a compile-time construct that indicates what a programmer should do, not necessarily what they cando. Note, however, that in the case of predefined data (such as const char * string literals), C const is oftenunwritable.In addition, a (non-static) member-function can be declared as const. In this case, the this pointer inside such afunction is of type return_value_type const * const rather than merely of typereturn_value_type * const. This means that non-const functions for this object cannot be called frominside such a function, nor can member variables be modified. In C++, a member variable can be declared asmutable, indicating that this restriction does not apply to it. In some cases, this can be useful, for example withcaching, reference counting, and data synchronization. In these cases, the logical meaning (state) of the object isunchanged, but the object is not physically constant since its bitwise representation may change.

C (and derived languages) syntaxIn C and derived languages, all data types, including those defined by the user, can be declared const, andconst-correctness dictates that all variables or objects should be declared as such unless they need to be modified.Such proactive use of const makes values "easier to understand, track, and reason about,"[1] and it thus increasesthe readability and comprehensibility of code and makes working in teams and maintaining code simpler because itcommunicates information about a value's intended use. This can help the compiler as well as the developer whenreasoning about code. It can also enable an optimizing compiler to generate more efficient code.

Simple data typesFor simple non-pointer data types, applying the const qualifier is straightforward. It can go on either side of thetype for historical reasons (that is, const char foo = 'a'; is equivalent to char const foo = 'a';).On some implementations, using const on both sides of the type (for instance, const char const) generatesa warning but not an error.

Pointers and referencesFor pointer and reference types, the meaning of const is more complicated – either the pointer itself, or the valuebeing pointed to, or both, can be const. Further, the syntax can be confusing. A pointer can be declared as aconst pointer to writable value, or a writable pointer to a const value, or const pointer to const value. Aconst pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can beused to modify the value that it points to (called the pointee). Reference variables are thus an alternate syntax forconst pointers. A pointer to a const object, on the other hand, can be reassigned to point to another memorylocation (which should be an object of the same type or of a convertible type), but it cannot be used to modify thememory that it is pointing to. A const pointer to a const object can also be declared and can neither be used tomodify the pointee nor be reassigned to point to another object. The following code illustrates these subtleties:

void Foo( int * ptr,

int const * ptrToConst,

int * const constPtr,

int const * const constPtrToConst )

Page 37: C++

Const-correctness 35

{

*ptr = 0; // OK: modifies the "pointee" data

ptr = NULL; // OK: modifies the pointer

*ptrToConst = 0; // Error! Cannot modify the "pointee" data

ptrToConst = NULL; // OK: modifies the pointer

*constPtr = 0; // OK: modifies the "pointee" data

constPtr = NULL; // Error! Cannot modify the pointer

*constPtrToConst = 0; // Error! Cannot modify the "pointee" data

constPtrToConst = NULL; // Error! Cannot modify the pointer

}

Following usual C convention for declarations, declaration follows use, and the * in a pointer is written on thepointer, indicating dereferencing. For example, in the declaration int *ptr, the dereferenced form *ptr is anint, while the reference form ptr is a pointer to an int. Thus const modifies the name to its right. The C++convention is instead to associate the * with the type, as in int* ptr, and read the const as modifying thetype to the left. int const * ptrToConst can thus be read as "*ptrToConst is a int const" (thevalue is constant), or "ptrToConst is a int const *" (the pointer is a pointer to a constant integer). Thus:

int *ptr; // *ptr is an int value

int const *ptrToConst; // *ptrToConst is a constant (int: integer

value)

int * const constPtr; // constPtr is a constant (int *: integer

pointer)

int const * const constPtrToConst; // constPtrToConst is a constant

(pointer)

// as is *constPtrToConst (value)

Following C++ convention of analyzing the type, not the value, a rule of thumb is to read the declaration from rightto left. Thus, everything to the left of the star can be identified as the pointee type and everything to the right of thestar are the pointer properties. For instance, in our example above, int const * can be read as a writable pointerthat refers to a non-writable integer, and int * const can be read as a non-writable pointer that refers to awritable integer.C/C++ also allows the const to be placed to the left of the type, in the following syntax:

const int* ptrToConst; //identical to: int const *

ptrToConst,

const int* const constPtrToConst;//identical to: int const * const

constPtrToConst

This more clearly separates the two locations for the const, and allows the * to always be bound to its precedingtype, though it still requires reading right-to-left, as follows:

int* ptr;

const int* ptrToConst; // (const int)*, not const (int*)

int* const constPtr;

const int* const constPtrToConst;

Page 38: C++

Const-correctness 36

Note, however, that despite the different convention for formatting C++ code, the semantics of pointer declarationare the same:

int* a; // a is an int pointer

int* a, b; // TRICKY: a is an int pointer as above, but b is not; b is

an int value

int* a, *b; // both a and b are pointers; *a and *b are int values

Bjarne Stroustrup's FAQ recommends only declaring one variable per line if using the C++ convention, to avoid thisissue.[2]

C++ references follow similar rules. A declaration of a const reference is redundant since references can never bemade to refer to another object:

int i = 22;

int const & refToConst = i; // OK

int & const constRef = i; // Error the "const" is redundant

Even more complicated declarations can result when using multidimensional arrays and references (or pointers) topointers; however, someWikipedia:Manual of Style/Words to watch#Unsupported attributions have argued that theseare confusing and error-prone and that they therefore should generally be avoided or replaced with higher-levelstructures.

Parameters and variablesconst can be declared both on function parameters and on variables (static or automatic, including global or local).The interpretation varies between uses. A const static variable (global variable or static local variable) is aconstant, and may be used for data like mathematical constants, such as const double PI = 3.14159 –realistically longer, or overall compile-time parameters. A const automatic variable (non-static local variable)means that single assignment is happening, though a different value may be used each time, such as const intx_squared = x*x. A const parameter in pass-by-reference means that the referenced value is not modified –it is part of the contract – while a const parameter in pass-by-value (or the pointer itself, in pass-by-reference)does not add anything to the interface (as the value has been copied), but indicates that internally, the function doesnot modify the parameter (it is a single assignment). For this reason, some favor using const in parameters onlyfor pass-by-reference, where it changes the contract, but not for pass-by-value, where it exposes the implementation.

MethodsIn order to take advantage of the design by contract approach for user-defined types (structs and classes), which canhave methods as well as member data, the programmer must tag instance methods as const if they don't modifythe object's data members. Applying the const qualifier to instance methods thus is an essential feature forconst-correctness, and is not available in many other object-oriented languages such as Java and C# or in Microsoft'sC++/CLI or Managed Extensions for C++. While const methods can be called by const and non-constobjects alike, non-const methods can only be invoked by non-const objects. The const modifier on an instancemethod applies to the object pointed to by the "this" pointer, which is an implicit argument passed to all instancemethods. Thus having const methods is a way to apply const-correctness to the implicit "this" pointer argumentjust like other arguments.This example illustrates:

class C

{

int i;

Page 39: C++

Const-correctness 37

public:

int Get() const // Note the "const" tag

{ return i; }

void Set(int j) // Note the lack of "const"

{ i = j; }

};

void Foo(C& nonConstC, const C& constC)

{

int y = nonConstC.Get(); // Ok

int x = constC.Get(); // Ok: Get() is const

nonConstC.Set(10); // Ok: nonConstC is modifiable

constC.Set(10); // Error! Set() is a non-const method and constC

is a const-qualified object

}

In the above code, the implicit "this" pointer to Set() has the type "C *const"; whereas the "this" pointerto Get() has type "const C *const", indicating that the method cannot modify its object through the "this"pointer.Often the programmer will supply both a const and a non-const method with the same name (but possibly quitedifferent uses) in a class to accommodate both types of callers. Consider:

class MyArray

{

int data[100];

public:

int & Get(int i) { return data[i]; }

int const & Get(int i) const { return data[i]; }

};

void Foo( MyArray & array, MyArray const & constArray )

{

// Get a reference to an array element

// and modify its referenced value.

array.Get( 5 ) = 42; // OK! (Calls: int & MyArray::Get(int))

constArray.Get( 5 ) = 42; // Error! (Calls: int const &

MyArray::Get(int) const)

}

The const-ness of the calling object determines which version of MyArray::Get() will be invoked and thuswhether or not the caller is given a reference with which he can manipulate or only observe the private data in theobject. The two methods technically have different signatures because their "this" pointers have different types,allowing the compiler to choose the right one. (Returning a const reference to an int, instead of merely returningthe int by value, may be overkill in the second method, but the same technique can be used for arbitrary types, asin the Standard Template Library.)

Page 40: C++

Const-correctness 38

Loopholes to const-correctnessThere are several loopholes to pure const-correctness in C and C++. They exist primarily for compatibility withexisting code.The first, which applies only to C++, is the use of const_cast, which allows the programmer to strip the constqualifier, making any object modifiable. The necessity of stripping the qualifier arises when using existing code andlibraries that cannot be modified but which are not const-correct. For instance, consider this code:

// Prototype for a function which we cannot change but which

// we know does not modify the pointee passed in.

void LibraryFunc(int *ptr, int size);

void CallLibraryFunc(int const *ptr, int size)

{

LibraryFunc(ptr, size); // Error! Drops const qualifier

int *nonConstPtr = const_cast<int*>(ptr); // Strip qualifier

LibraryFunc(nonConstPtr, size); // OK

}

However, any attempt to modify an object that is itself declared const by means of const_cast results inundefined behavior according to the ISO C++ Standard. In the example above, if ptr references a global, local, ormember variable declared as const, or an object allocated on the heap via new const int, the code is onlycorrect if LibraryFunc really does not modify the value pointed to by ptr.The C language has a need of a loophole because a certain situation exists. Variables with static storage duration areallowed to be defined with an initial value. However, the initializer can use only constants like string constants andother literals, and are not allowed to use non-constant elements like variable names, whether the initializer elementsare declared const or not, or whether the static duration variable is being declared const or not. There is anon-portable way to initialize a const variable that has static storage duration. By carefully constructing a typecaston the left hand side of a later assignment, a const variable can be written to, effectively stripping away theconst attribute and 'initializing' it with non-constant elements like other const variables and such. Writing into aconst variable this way may work as intended, but it causes undefined behavior and seriously contradictsconst-correctness:

const size_t bufferSize = 8*1024;

const size_t userTextBufferSize; //initial value depends on const

bufferSize, can't be initialized here

...

int setupUserTextBox(textBox_t *defaultTextBoxType, rect_t

*defaultTextBoxLocation)

{

*(size_t*)&userTextBufferSize = bufferSize - sizeof(struct

textBoxControls); // warning: might work, but not guaranteed by C

...

}

Another loopholeWikipedia:Citation needed applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the const-ness of their owners — that is, a

Page 41: C++

Const-correctness 39

containing object that is const has all const members except that member pointees (and referees) are stillmutable. To illustrate, consider this code:

struct S

{

int val;

int *ptr;

};

void Foo(const S & s)

{

int i = 42;

s.val = i; // Error: s is const, so val is a const int

s.ptr = &i; // Error: s is const, so ptr is a const pointer to int

*s.ptr = i; // OK: the data pointed to by ptr is always mutable,

// even though this is sometimes not desirable

}

Although the object s passed to Foo() is constant, which makes all of its members constant, the pointeeaccessible through s.ptr is still modifiable, though this may not be desirable from the standpoint ofconst-correctness because s might solely own the pointee. For this reason, someWikipedia:Manual ofStyle/Words to watch#Unsupported attributions have argued that the default for member pointers and referencesshould be "deep" const-ness, which could be overridden by a mutable qualifier when the pointee is not ownedby the container, but this strategy would create compatibility issues with existing code. Thus, for historicalreasonsWikipedia:Citation needed, this loophole remains open in C and C++.The latter loophole can be closed by using a class to hide the pointer behind a const-correct interface, but suchclasses either don't support the usual copy semantics from a const object (implying that the containing classcannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of const-nessthrough inadvertent or intentional copying.Finally, several functions in the C standard library violate const-correctness, as they accept a const pointer to acharacter string and return a non-const pointer to a part of the same string. strtol and strchr are amongthese functions. Some implementations of the C++ standard library, such as Microsoft's try to close this loophole byproviding two overloaded versions of some functions: a "const" version and a "non-const" version.

Volatile-correctnessThe other qualifier in C and C++, volatile, indicates that an object may be changed by something external to theprogram at any time and so must be re-read from memory every time it is accessed.The qualifier is most often found in code that manipulates hardware directly (such as in embedded systems anddevice drivers) and in multithreaded applications (though often used incorrectly in that context; see external links atvolatile variable). It can be used in exactly the same manner as const in declarations of variables, pointers,references, and member functions, and in fact, volatile is sometimes used to implement a similardesign-by-contract strategy which Andrei Alexandrescu calls volatile-correctness,[3] though this is far lesscommon than const-correctness. The volatile qualifier also can be stripped by const_cast, and it can becombined with the const qualifier as in this sample:

// Set up a reference to a read-only hardware register that is

// mapped in a hard-coded memory location.

const volatile int & hardwareRegister = *reinterpret_cast<int*>(0x8000);

Page 42: C++

Const-correctness 40

int currentValue = hardwareRegister; // Read the memory location

int newValue = hardwareRegister; // Read it again

hardwareRegister = 5; // Error! Cannot write to a const location

Because hardwareRegister is volatile, there is no guarantee that it will hold the same value on twosuccessive reads even though the programmer cannot modify it. The semantics here indicate that the register's valueis read-only but not necessarily unchanging.

const and immutable in DIn Version 2 of the D programming language, two keywords relating to const exist. The immutable keyworddenotes data that cannot be modified through any reference. The const keyword denotes a non-mutable view ofmutable data. Unlike C++ const, D const and immutable are "deep" or transitive, and anything reachablethrough a const or immutable object is const or immutable respectively.Example of const vs. immutable in D

int[] foo = new int[5]; // foo is mutable.

const int[] bar = foo; // bar is a const view of mutable data.

immutable int[] baz = foo; // Error: all views of immutable data must

be immutable.

immutable int[] nums = new immutable(int)[5]; // No mutable reference

to nums may be created.

const int[] constNums = nums; // Works. immutable is implicitly

convertible to const.

int[] mutableNums = nums; // Error: Cannot create a mutable view of

immutable data.

Example of transitive or deep const in D

class Foo {

Foo next;

int num;

}

immutable Foo foo = new immutable(Foo);

foo.next.num = 5; // Won't compile. foo.next is of type

immutable(Foo).

// foo.next.num is of type immutable(int).

Page 43: C++

Const-correctness 41

final in JavaIn Java, the qualifier final states that the affected data member or variable is not assignable, as below:

final int i = 3;

i = 4; // Error! Cannot modify a "final" object

It must be decidable by the compilers where the variable with the final marker is initialized, and it must beperformed only once, or the class will not compile. Java's final and C++'s const keywords have the samemeaning when applied with primitive variables.

const int i = 3; // C++ declaration

i = 4; // Error!

Considering pointers, a final reference in Java means something similar to const pointer in C++. In C++, onecan declare a "const pointer type".

Foo *const bar = mem_location; // const pointer type

Here, bar must be initialised at the time of declaration and cannot be changed again, but what it points ismodifiable. I.e. *bar = value is valid. It just can't point to another location. Final reference in Java work thesame way except it can be declared uninitialized.

final Foo i; // a Java declaration

Note: Java does not support pointers. It is because pointers (with restrictions) are the default way of accessingobjects in Java, and Java does not use stars to indicate them. For example i in the last example is a pointer and canbe used to access the instance.One can also declare a pointer to "read-only" data in C++.

const Foo *bar;

Here bar can be modified to point anything, anytime; just that pointed value cannot be modified through barpointer. There is no equivalent mechanism in Java. Thus there are also no const methods. Const-correctnesscannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passingthis around, one can ensure that objects can be passed around the system in a way that they cannot be modified. Javacollections framework provides a way to create unmodifiable wrapper of a Collection viaCollections.unmodifiableCollection() and similar methods.Methods in Java can be declared "final", but that has a completely unrelated meaning - it means that the methodcannot be overridden in subclasses.Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be usedas variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred toallow for an extension of the Java language to include C++-style const methods and pointer to consttype.Wikipedia:Citation needed An enhancement request ticket for implementing const correctness exists in theJava Community Process, but was closed in 2005 on the basis that it was impossible to implement in abackwards-compatible fashion.

Page 44: C++

Const-correctness 42

const and readonly in C#In C#, the qualifier readonly has the same effect on data members that final does in Java and the constdoes in C++; the const modifier in C# has an effect similar (yet typed and class-scoped) to that of #define inC++. (The other, inheritance-inhibiting effect of Java's final when applied to methods and classes is induced inC# with the aid of a third keyword, sealed.)Unlike C++, C# does not permit methods and parameters to be marked as const. However one may also passaround read-only subclasses, and the .NET Framework provides some support for converting mutable collections toimmutable ones which may be passed as read-only wrappers.

References[1] Herb Sutter and Andrei Alexandrescu (2005). C++ Coding Standards. p. 30. Boston: Addison Wesley. ISBN 0-321-11358-6[2] http:/ / www. stroustrup. com/ bs_faq2. html#whitespace[3] "Generic<Programming>: volatile — Multithreaded Programmer's Best Friend Volatile-Correctness or How to Have Your Compiler Detect

Race Conditions for You" (http:/ / www. drdobbs. com/ cpp/ 184403766) by Andrei Alexandrescu in the C/C++ Users Journal C++ ExpertsForum

External links• "Const-Correctness" (http:/ / gotw. ca/ gotw/ 006. htm) by Herb Sutter• "Constant Optimization?" (http:/ / gotw. ca/ gotw/ 081. htm) by Herb Sutter• "Const-Correctness Tutorial" (http:/ / cprogramming. com/ tutorial/ const_correctness. html) by

Cprogramming.com• The C++ FAQ Lite: Const correctness (http:/ / parashift. com/ c+ + -faq-lite/ const-correctness. html) by Marshall

Cline• Section " Value substitution (http:/ / www. mi. uni-koeln. de/ c/ mirror/ www. codeguru. com/ cpp/ tic/ tic_html.

zip/ tic0092. html)" from the free electronic book Thinking in C++ by Bruce Eckel• "Here A Const, There A Const" (http:/ / www. digitalmars. com/ d/ const. html) by Walter Bright• "Const and Invariant" from D programming language specification, version 2 (experimental) (http:/ / www.

digitalmars. com/ d/ 2. 0/ const3. html)• Some notes on const correctness in straight C in "C Pointer Qualifiers" (http:/ / www. thomasstover. com/

c_pointer_qualifiers. html) by Thomas Stover

Page 45: C++

Virtual function 43

Virtual function

Polymorphism•• Ad hoc polymorphism•• Function overloading•• Operator overloading•• Parametric polymorphism•• Double dispatch•• Multiple dispatch• Single & dynamic dispatch•• Subtyping•• Virtual function

•• v•• t• e [1]

In object-oriented programming, a virtual function or virtual method is a function or method whose behavior canbe overridden within an inheriting class by a function with the same signature. This concept is an important part ofthe polymorphism portion of object-oriented programming (OOP).

PurposeFurther information: Dynamic dispatchThe concept of the virtual function solves the following problem:In object-oriented programming when a derived class inherits from a base class, an object of the derived class maybe referred to via a pointer or reference of the base class type instead of the derived class type. If there are base classmethods overridden by the derived class, the method actually called by such a reference or pointer can be boundeither 'early' (by the compiler), according to the declared type of the pointer or reference, or 'late' (i.e. by the runtimesystem of the language), according to the actual type of the object referred to.Virtual functions are resolved 'late'. If the function in question is 'virtual' in the base class, the most-derived class'simplementation of the function is called according to the actual type of the object referred to, regardless of thedeclared type of the pointer or reference. If it is not 'virtual', the method is resolved 'early' and the function called isselected according to the declared type of the pointer or reference.Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code iscompiled.In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the baseclass. This modifier is inherited by all implementations of that method in derived classes, meaning that they cancontinue to over-ride each other and be late-bound.

Page 46: C++

Virtual function 44

Example

Class Diagram of Animal

For example, a base class Animalcould have a virtual function eat.Subclass Fish would implementeat() differently than subclassWolf, but one can invoke eat() onany class instance referred to asAnimal, and get the eat() behaviorof the specific subclass.

class Animal

{

void /*nonvirtual*/ move() {

cout << "This animal moves in some way" << endl;

}

virtual void eat() {}

};

// The class "Animal" may possess a declaration for eat() if desired.

class Llama : public Animal

{

// The non virtual function move() is inherited but cannot be

overridden

void eat() {

cout << "Llamas eat grass!" << endl;

}

};

This allows a programmer to process a list of objects of class Animal, telling each in turn to eat (by callingeat()), without needing to know what kind of animal may be in the list, how each animal eats, or what thecomplete set of possible animal types might be.

Abstract classes and pure virtual functionsA pure virtual function or pure virtual method is a virtual function that is required to be implemented by aderived class if that class is not abstract. Classes containing pure virtual methods are termed "abstract" and theycannot be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited purevirtual methods have been implemented by that class or a parent class. Pure virtual methods typically have adeclaration (signature) and no definition (implementation).As an example, an abstract base class MathSymbol may provide a pure virtual function doOperation(), and derived classes Plus and Minus implement doOperation() to provide concrete implementations. Implementing doOperation() would not make sense in the MathSymbol class, as MathSymbol is an

Page 47: C++

Virtual function 45

abstract concept whose behaviour is defined solely for each given kind (subclass) of MathSymbol. Similarly, agiven subclass of MathSymbol would not be complete without an implementation of doOperation().Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methodsin C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviourthat a derived class can delegate to, if appropriate.Pure virtual functions can also be used where the method declarations are being used to define an interface - similarto what the interface keyword in Java explicitly specifies. In such a use, derived classes will supply allimplementations. In such a design pattern, the abstract class which serves as an interface will contain only purevirtual functions, but no data members or ordinary methods. In C++, using such purely abstract classes as interfacesworks because C++ supports multiple inheritance. However, because many OOP languages do not support multipleinheritance, they often provide a separate interface mechanism. An example is the Java programming language.

Behavior during construction and destructionLanguages differ in their behavior while the constructor or destructor of an object is running. For some languages,notably C++, the virtual dispatching mechanism has different semantics during construction and destruction of anobject. While it is recommended that virtual function calls in constructors should be avoided for C++, in some otherlanguages, for example C# and Java, the derived implementation can be called during construction and designpatterns such as the Abstract Factory Pattern actively promote this usage in languages supporting the ability.

Virtual destructorsObject-oriented languages typically manage memory allocation and de-allocation automatically when objects arecreated and destroyed. However, some object-oriented languages allow a custom destructor method to beimplemented, if desired. If the language in question uses automatic memory management, the custom destructor(generally called a finalizer in this context) that is called is certain to be the appropriate one for the object inquestion. For example, if an object of type Wolf that inherits Animal is created, and both have custom destructors,the one called will be the one declared in Wolf.In manual memory management contexts, the situation can be more complex, particularly as relates to staticdispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer typethat is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless thedestructor is virtual. This is particularly the case with C++, where the behavior is a common source of programmingerrors.

References[1] http:/ / en. wikipedia. org/ w/ index. php?title=Template:Polymorphism& action=edit

Page 48: C++

Template (C++) 46

Template (C++)Templates are a feature of the C++ programming language that allow functions and classes to operate with generictypes. This allows a function or class to work on many different data types without being rewritten for each one.Templates are of great utility to programmers in C++, especially when combined with multiple inheritance andoperator overloading. The C++ Standard Library provides many useful functions within a framework of connectedtemplates.Major inspirations for C++ templates were the parametrized modules provided by CLU and the generics provided byAda.

Technical overviewThere are two kinds of templates: function templates and class templates. (A third kind, variable templates, isexpected to feature in C++14.)

Function templatesA function template behaves like a function except that the template can have arguments of many different types (seeexample). In other words, a function template represents a family of functions. The format for declaring functiontemplates with type parameters is

template <class identifier> function_declaration;

template <typename identifier> function_declaration;

Both expressions have exactly the same meaning and behave exactly the same way. The latter form was introducedto avoid confusion because a type parameter does not need to be a class, it may also be a basic type like int ordoubleWikipedia:Citation needed.For example, the C++ Standard Library contains the function template max(x, y) which returns either x or y,whichever is larger. max() could be defined with the following template:

//This example throws the following error : call of overloaded

'max(double, double)' is ambiguous

template <typename Type>

Type max(Type a, Type b) {

return a > b ? a : b;

}

This single function definition works with many data types. Although usage of a function template saves space in thesource code file (in addition to limiting changes to one function description) versus separate functions written forvarious datatypes, it does not produce smaller object code than would occur from separate non-templated versions ofa function written for different types. For example, if a program uses an int and a double version of the max()function template shown above, the compiler will create an object code version of max() that takes ints and an objectcode version that takes doubles. The compiler output will be identical to what would have been produced if thesource code contained two non-templated versions of max(), one written to handle ints and one written to handledoubles.

#include <iostream>

int main(int, char**)

{

Page 49: C++

Template (C++) 47

// This will call max <int> (by argument deduction)

std::cout << max(3, 7) << std::endl;

// This will call max<double> (by argument deduction)

std::cout << max(3.0, 7.0) << std::endl;

// This type is ambiguous, so explicitly instantiate max<double>

std::cout << max<double>(3, 7.0) << std::endl;

return 0;

}

In the first two cases, the template argument Type is automatically deduced by the compiler to be int anddouble, respectively. In the third case deduction fails because the type of the parameters must in general match thetemplate arguments exactly. This function template can be instantiated with any copy-constructible type for whichthe expression (y < x) is valid. For user-defined types, this implies that the less-than operator must be overloaded.

Class templatesA class template provides a specification for generating classes based on parameters. Class templates are generallyused to implement containers. A class template is instantiated by passing a given set of types to it as templatearguments. The C++ Standard Library contains many class templates, in particular the containers adapted from theStandard Template Library, such as vector.

Template specializationWhen a function or class is instantiated from a template, a specialization of that template is created by the compilerfor the set of arguments used, and the specialization is referred to as being a generated specialization.

Explicit template specializationSometimes, the programmer may decide to implement a special version of a function (or class) for a given set oftemplate type arguments which is called an explicit specialization. In this way certain template types can have aspecialized implementation that is optimized for the type or more meaningful implementation than the genericimplementation.• If a class template is specialized by a subset of its parameters it is called partial template specialization (function

templates cannot be partially specialized).• If all of the parameters are specialized it is a full specialization.Explicit specialization is used when the behavior of a function or class for particular choices of the templateparameters must deviate from the generic behavior: that is, from the code generated by the main template, ortemplates. For example, the template definition below defines a specific implementation of template "max" for type"bool":

template <>

bool max<bool>(bool a, bool b) {

return a || b;

}

Page 50: C++

Template (C++) 48

Variadic templatesC++11 introduced variadic templates, which can take a variable number of arguments in a manner somewhat similarto variadic functions such as std::printf. Both function templates and class templates can be variadic.

Advantages and disadvantagesSome uses of templates, such as the maximum() function, were previously fulfilled by function-like preprocessormacros. For example, the following is a C++ maximum() macro:

#define maximum(a,b) ((a) < (b) ? (b) : (a))

Both macros and templates are expanded at compile time. Macros are always expanded inline, while templates areonly expanded inline when the compiler deems it appropriate. When expanded inline, macro functions and functiontemplates have no extraneous runtime overhead. Template functions with many lines of code will incur runtimeoverhead when they are not expanded inline, but the reduction in code size may help the code to load from disk morequickly or fit within RAM caches.Templates are considered type-safe; that is, they require type-checking at compile time. Hence, the compiler candetermine at compile time whether the type associated with a template definition can perform all of the functionsrequired by that template definition.By design, templates can be utilized in very complex problem spaces, whereas macros are substantially more limited.There are fundamental drawbacks to the use of templates:1.1. Historically, some compilers exhibited poor support for templates. So, the use of templates could decrease code

portability.2. Many compilers lack clear instructions when they detect a template definition error. This can increase the effort

of developing templates, and has prompted the development of Concepts for possible inclusion in a future C++standard.

3. Since the compiler generates additional code for each template type, indiscriminate use of templates can lead tocode bloat, resulting in larger executables.

4.4. Because a template by its nature exposes its implementation, injudicious use in large systems can lead to longerbuild times.

5. It can be difficult to debug code that is developed using templates. Since the compiler replaces the templates, itbecomes difficult for the debugger to locate the code at runtime.

6.6. Templates of Templates (nesting) are not supported by all compilers, or might have a max nesting level.7.7. Templates are in the headers, which require a complete rebuild of all project pieces when changes are made.8.8. No information hiding. All code is exposed in the header file. No one library can solely contain the code.Additionally, the use of the "less than" and "greater than" signs as delimiters is problematic for tools (such as texteditors) which analyze source code syntactically. It is difficult for such tools to determine whether a use of thesetokens is as comparison operators or template delimiters. For example, this line of code:

foo (a < b, c > d) ;

may be a function call with two parameters, each the result of a comparison expression. Alternatively, it could be adeclaration of a constructor for class foo taking a parameter d whose type is the parameterized a < b, c >.

Page 51: C++

Template (C++) 49

Generic programming features in other languagesInitially, the concept of templates was not included in some languages, such as Java and C# 1.0. Java's adoption ofgenerics mimics the behaviour of templates, but is technically different. C# added generics (parameterized types) in.NET 2.0. The generics in Ada predate C++ templates.Although C++ templates, Java generics, and .NET generics are often considered similar, generics only mimic thebasic behavior of C++ templates.[1] Some of the advanced template features utilized by libraries such as Boost andSTLSoft, and implementations of the STL itself, for template metaprogramming (explicit or partial specialization,default template arguments, template non-type arguments, template template arguments, ...) are not available withgenerics.The D programming language attempts to build on C++ redesigning a better template system.[2] A significantaddition is the inclusion of the static if statement, which allows conditional compilation of code based on anyinformation known at compile time. For example:

template factorial(ulong n)

{

static if( n <= 1 )

const factorial = 1;

else

const factorial = n * factorial!(n-1);

};

D's CTFE (Compile time function execution) feature allows to do the same thing :

ulong factorial(ulong n)

{

if(n <= 1)

return 1;

else

return n * factorial(n - 1);

}

void main()

{

ulong foo = factorial(4); // known at run-time

static foo2 = factorial(4); // known at compile-time

}

Also note that the !() delimiters are used rather than the <> delimiters. This prevents ambiguity in the parsing oftemplates.Other significant features include typesafe variadic template functions.

// Simple example, assumes all arguments are of the same type.

T[0] max(T...)(T args) {

static assert(args.length > 1, "Insufficient arguments.");

// T[0] is the type of the first argument,

// args[0] is the first argument.

T[0] max = args[0];

// Tuple can be iterated over and sliced like an array.

foreach (arg; args[1 .. $])

Page 52: C++

Template (C++) 50

if (arg > max)

max = arg;

return max;

}

This function will work for any number of arguments, with the foreach iteration over the tuple of argumentsexpanded at compile time.D templates allow a simple form of Constraints too. They can be expressed as an arbitrarily complex predicate thatmust evaluate at compile time. If it's true the template is a match for the arguments, otherwise the template is ignoredduring overload matching.[3]

template Foo(int N) if (N & 1) {...} // A

template Foo(int N) if (!(N & 1)) {...} // B

Foo!(3) // Instantiates A

Foo!(64) // Instantiates B

template Bar(T) if (isFloatingPoint!T) {...}

Bar!(3.5) // Instantiates Bar

Bar!(3) // Fails

Something similar can be done in C++ with Boost enable_if,[4] or with the std::enable_if introduced in C++11.In C++ templates, the compile-time cases are performed by pattern matching over the template arguments, so theFactorial template's base case is implemented by matching 0 rather than with an inequality test, which is unavailable:

// Induction

template <int N>

struct Factorial {

static const int value = N * Factorial<N - 1>::value;

};

// Base case via template specialization:

template <>

struct Factorial<0> {

static const int value = 1;

};

With these definitions, one can compute, say 6! at compile time using the expression Factorial<6>::value.

Page 53: C++

Template (C++) 51

References[1] Differences Between C++ Templates and C# Generics (C# Programming Guide) (http:/ / msdn2. microsoft. com/ en-us/ library/ c6cyy67b.

aspx)[2] (D) Templates Revisited (http:/ / dlang. org/ templates-revisited. html)[3] (D) Template Constraints (http:/ / dlang. org/ concepts. html)[4] Boost enable_if templates (http:/ / www. boost. org/ doc/ libs/ 1_42_0/ libs/ utility/ enable_if. html)

External links• Demonstration of the Turing-completeness of C++ templates (http:/ / matt. might. net/ articles/ c+ +

-template-meta-programming-with-lambda-calculus/ ) (Lambda calculus implementation)

Page 54: C++

Article Sources and Contributors 52

Article Sources and ContributorsC++  Source: http://en.wikipedia.org/w/index.php?oldid=616785470  Contributors: -Barry-, 12.21.224.xxx, 1exec1, 223ankher, 28bytes, 4jobs, 4th-otaku, 7DaysForgotten, @modi, A D MonroeIII, A Jav, A.A.Graff, A930913, AIOS, ALOTOFTOMATOES, AMackenzie, ANXIOUS117, AOC25, ARSchmitz, AThing, ATren, Aandu, AbcdefgTROLL, Abdull, Abi79, Abledsoe78,Abolitionhf, Abstractematics, Access Denied, Adam12901, Addihockey10, Adi211095, Adorno rocks, Adrianwn, Ae-a, Aesopos, AgadaUrbanit, Agasta, AgentFriday, Ahmadmashhour,Ahoerstemeier, Ahy1, Akeegazooka, Akersmc, Akhristov, Akihabara, Akuyume, Alan D, Alan Liefting, AlbertCahalan, AlecSchueler, Aleenf1, AleksanderVatov, AlexKarpman, Alexf,Alexius08, Alexkon, Alfio, Alhoori, Aliekens, AlistairMcMillan, Allstarecho, Alpha Quadrant (alt), AltiusBimm, Alxeedo, AnAccount2, AnOddName, Ananddhage710, Andante1980, AndreEngels, Andreaskem, Andrew Delong, Andrew1, AndrewHowse, AndrewKepert, Andyluciano, Angbor, AngelOfSadness, Angela, Anoko moonlight, AnonMoos, Anonymous Dissident,Antandrus, Aparna.amar.patil, Apexofservice, Apokryltaros, Arabic Pilot, Aragorn2, Arcadie, Arctic.gnome, Ardonik, ArglebargleIV, AshishDandekar7, Asimzb, Astrobunny, Astronautics,Atjesse, Atlant, Auntof6, Austin Hair, Autopilot, Avoided, Avoran, Axecution, AxelBoldt, BD2412, BMW Z3, Baa, Babija, Babjisit, Backdoor2world, Bahram.zahir, Barek, Barkha dhamechai,Baronnet, Bart133, Bartosz, Bdragon, Bduke, Beland, Belem tower, BenFrantzDale, Benhocking, Bento00, Beowulf king, Bereajan, Bevo, Beyondthislife, Bfzhao, Bgwhite, Bhahas,Biblioth3que, BigChrill, Bigk105, Bill gates69, Billj321, Billyoneal, Bineet, Bkil, Blaisorblade, BlitzGreg, Bluemoose, Bluezy, Bobazoid, Bobblewik, Bober71, Bobo192, Bobthebill, Bodkinator,Boffob, Boing! said Zebedee, Bomarrow1, Bonadea, Bongwarrior, Booklegger, Boseko, Bovineone, Brion VIBBER, Btx40, C Labombard, C++ Template, C.Fred, CALR, CIreland, CPMcE,CRGreathouse, CTZMSC3, CWY2190, Caesura, Caiaffa, Callek, Caltas, Can't sleep, clown will eat me, CanisRufus, Canthusus, Cap'n Refsmmat, Capi crimm, CapitalR, Capricorn42,Captainhampton, Carabinieri, Carbon editor, Card Zero, Carlson-steve, Carnivorousfungi, Catgut, Cathack, CecilWard, Cedars, CesarB, Cetinsert, Cfeet77, Cflm001, Cgranade, Chaos5023,CharlotteWebb, Chealer, Cherkash, ChessKnught, Chocolateboy, ChrisGualtieri, Chrisandtaund, Christian List, Chrsimon, Chuq, Ckburke, Clay, Claystu, Cleared as filed, Closedmouth,Clsdennis2007, Coasterlover1994, Code-Analysis, Cometstyles, Comperr, Compfreak7, Conversion script, Coolwanglu, Coosbane, Coq Rouge, CordeliaNaismith, Corrector7007, Corti,Cowsnatcher27, Cpiral, Craig Stuntz, Crashnburn2007, Crotmate, Cryptic, Csmaster2005, Ctu2485, Cubbi, Curb Chain, Curps, Cwitty, Cybercobra, Cyclonenim, Cyde, CyrilleDunant, Cyrius,DAGwyn, DJ Clayworth, DVD R W, DVdm, Dallison999, Damian Yerrick, Damien.c.sadler, Dan Brown123, Dan Harkless, Dan100, Danakil, Danger, Daniel Earwicker, Daniel.Cardenas,Daniel347x, DanielNuyu, Danim, Darestium, Dario D., DarkHorizon, Darkmonkeyz321, Darolew, Dave Runger, Daverose 33, David A Bozzini, David H Braun (1964), Davidking20, DawnBard, Dawnseeker2000, Dch888, Dcoetzee, De728631, Decltype, Deflective, Deibid, Delirium, Delldot, Demonkoryu, Denelson83, DerHexer, Derek Ross, Deryck Chan, DevSolar,DevastatorIIC, Devengosalia514, Dewritech, Dhs India, Diannaa, Dibash, DigitalMediaSage, Dipaliraut, Dirkbb, Discospinster, Dlae, Dlfkja;lskj, Dmharvey, Dnstory, Dogcow, DominicConnor,DonelleDer, Donhalcon, Donner60, Doofenschmirtzevilinc, DopeWare, DoubleRing, Doug Bell, Dougjih, Doulos Christos, Drangon, Drewcifer3000, Drrngrvy, Dsimic, Dylnuge, Dysprosia,Dystopiavirus, E Wing, ESkog, Eagleal, Ebeisher, Ecallow, Eco84, Ecstatickid, Ed Brey, Editorplus123, Edward Z. Yang, EdwardH, Eeekster, Eelis, Eelis.net, Ehn, Elitewinner, Elliskev, ElvenSpellmaker, Elysdir, Enarsee, EncMstr, Enerjazzer, EngineerScotty, Entropy, Eric119, ErikHaugen, Esanchez7587, Esben, Esmito, Esrogs, Eternaldescent08, Ethan, EvanED, Evanh2008, Evice,Evil Monkey, Ewok18, ExcessPhase, Excirial, FW4NK, Fa2sA, FaTony, Fabiwanne, Facorread, Faithlessthewonderboy, Faizni, Falcon300000, Fanf, Faramir1138, Fashionslide, FatalError,Favonian, Fistboy, Fizzackerly, Flamingantichimp, Flewis, Flex, Florian Weber, Fluffernutter, Flyingprogrammer, Forderud, FrancoGG, Franl, François Robere, Freakofnurture, Frecklefoot, FreeSoftware Knight, Fresheneesz, Fritzpoll, Ftbhrygvn, Furby100, Furrykef, Fuzzybyte, Fyyer, GDallimore, GENtLe, GLari, Galois fu, Gareth Griffith-Jones, Gaul, Gauss, Ged UK, Geeoharee,Gene.thomas, Gengiskanhg, Genhuan, Georg Peter, Giftlite, Gil mo, Gildos, Gilgamesh, Gilliam, Gimili2, Glacialfox, God Of All, Gogo Dodo, GoingBatty, Gondawer, GoodSirJava,GorillaWarfare, Graue, Greatdebtor, GregorB, Gremagor, Grenavitar, Grey GosHawk, Grigor The Ox, GroovySandwich, Gsonnenf, Gunman000, Gusmoe, Gwern, Gwjames, Hairy Dude,Hakkinen, Hamtechperson, Handheldpenguin, Hans Bauer, HappyCamper, Harald Hansen, Harinisanthosh, Harryboyles, Hasarel, HebrewHammerTime, HeikoEvermann, Hemanshu, HenryLi,Herorev, Hervegirod, Hetar, Hgfernan, HideandLeek, Hihahiha474, Hiraku.n, Hmains, Hobartimus, Hogman500, Horselover Frost, Hoss7994, Hto9950, Hu, Hu12, HueSatLum, Husond, Hyad,Hyperfusion, I already forgot, I am One of Many, ISoLoveHer, Iamninja91, Ibmarul, Ibroadfo, Iliealldaylong, Imc, Immunize, InShaneee, Innoncent, Insanity Incarnate, Intangir, Intelati,InvertedSaint, Iphoneorange, Ipsign, Iridescence, Iridescent, Irish Souffle, Ironholds, Isaacl, Iuliatoyo, Ixfd64, J Casanova, J Di, J-A-V-A, J.Dong820, J.delanoy, JForget, JNighthawk, Jackelfive,Jafet, James086, JamesKripke, Jarble, Jaredwf, Jason Quinn, Jatos, Javiercastillo73, Javierito92, Jawed, Jayaram ganapathy, Jdent29, Jdowland, Jeff G., JeffTL, Jeltz, Jerry teps, Jerryobject,Jeshan, Jesse Viviano, JesseW, Jfmantis, Jgamer509, Jgrahn, Jgroenen, Jh51681, Jigen III, Jim1138, Jimsve, Jizzbug, Jk2q3jrklse, Jlin, Jnestorius, JoaquinFerrero, John Cline, Johndci, Johnsolo,Johnuniq, Jojo966, Jok2000, Jon701, Jonathan Grynspan, Jonathanischoice, Jonel, Jonesey95, Jonmon6691, Jorend, Josh Cherry, Juliano, Julienlecomte, Junkyboy55, Jyotirmay dewangan, K3rb,KJK::Hyperion, KTC, Kaimason1, Kajasudhakarababu, Kalanaki, Kallikanzarid, Kanakid200, Kangaroopower, Kapil87852007, Kashami, Kate, Keilana, Kentij, Khym Chanur, Kifcaliph, Kingof Hearts, Kinu, Kkm010, Klassobanieras, Kleuske, Klilidiplomus, Kmerr, KnowledgeOfSelf, Kogz, Kooky, Korath, Korval, Koyaanis Qatsi, Krelborne, Kri, Krich, Krischik, Kristjan.Jonasson,KryptonX, Ksam, Kuru, Kusunose, Kwamikagami, Kwertii, Kxx, Kyle2^32-1, Kyleahampton, Landon1980, Larry V, Lars Washington, Lastplacer, Le Funtime Frankie, Lee Daniel Crocker,LeinadSpoon, Lepreshaun, Leszek Jańczuk, Liao, Liftarn, Lightmouse, Ligulem, Lilac Soul, Lilpony6225, Lir, Liujiang, Lkdude, Lloyd Wood, Loadmaster, Locos epraix, Logixoul, Lost.goblin,Lotje, Lovetinkle, Lowellian, Luks, Lvella, Lysander89, MER-C, Mabdul, Machekku, MadCow257, Mahadev00000, Mahanga, Maheshchowdary, Makecat, Male1979, Malfuf, Malhonen,Malleus Fatuorum, Mani1, Manifestation, Manjo mandruva, Manofabluedog, Manolis69, MarSch, Marc Mongenet, Marc-André Aßbrock, Marc-russo, Marcelo Pinto, Mark Arsten, Mark Foskey,Marktillinghast, Marqmike2, Martarius, Masterkilla, Materialscientist, Mathrick, Mathsum.mut, Mato, Matt.forestpath, MattGiuca, Matthewp1998, Matthieu fr, Mav, Mavarok, Max Schwarz,Maxim, Mayank15 5, Mbecker, Mccoyst, Mcorazao, Mcstrother, Mean as custard, Mecanismo, MelbourneStar, Mellum, Melonkelon, MeltBanana, Mentifisto, Mequa, Meshach, Metamatic,Meters, Methcub, MetsFan76, Mfwitten, Mhadoks12, Mhnin0, MichaelJHuman, Michaeltarpley, Micphi, Mifter, MihaS, Mikademus, Mike Rosoft, Mike Van Emmerik, Mike92591, MikrosamAkademija 7, MilesMi, Millahnna, Milo03, Mindmatrix, Minesweeper, Minghong, Minimac, Mipadi, Miqademus, Miracleworker5263, Miranda, Mirror Vax, Mistersooreams, Misuo,Mjoldaccount, Mjquinn id, Mkarlesky, Mkcmkc, Mkhan3189, Mmeijeri, Mmugundhann, MoA)gnome, Moanzhu, Modify, Mogism, Mohamed Magdy, Mole2386, MoreNet, Morgankevinj,Mortense, Morwen, Moxfyre, Mptb3, Mr MaRo, Mr.GATES987, MrOllie, MrSomeone, MrX, Mrjeff, Mrwes95, Ms2ger, Mthinkcpp, Muchness, Mukis, Muneermpballa, Muon, Muralive,MusikAnimal, MustafaeneS, Mxn, Myasuda, Myconix, Mycplus, Myork, Mystìc, N111111KKKKKKKooooo, Naddy, Nanshu, Napi, Nasa-verve, Natdaniels, Nathan2055, NawlinWiki, Nbarth,Negashek, Neilc, Nertal, Neurolysis, NevilleDNZ, Newsmen, Nfcopier, Nick, Nickjames90, Nicsterr, Niels Dekker, Ninly, Nintendude, Nirdh, Nisheet88, Nixdorf, Nixeagle, Njaard, Nma wiki,Nodekeeper, Nohat, Noldoaran, Non-dropframe, Noobs2007, Noosentaal, Northernhenge, Ntsimp, ORBIT, OUDave4m, Odddoe323, Oddity-, Odinjobs, Ohnoitsjamie, Ojuice, OldakQuill, OlegAlexandrov, Oliver202, Omnipaedista, Oneiros, Oranjelo100, Ouraqt, OutRIAAge, OverlordQ, OwenBlacker, Ozjimbob, Ozzmosis, Paddu, Padmaja cool, Pak21, Panarchy, Pankajwillis,ParallelWolverine, Paul Stansifer, Paul evans, Paulcmnt, Paulius2003, Pavel Vozenilek, Pawanindia2009, Pbroks13, Pcb21, Pde, PeaceNT, Pedant17, Peruvianllama, Peterl, Peteturtle, Petiatil,Pgk, Pharaoh of the Wizards, Pharos, Phil Boswell, Philip Trueman, PhilippWeissenbacher, Phoe6, Pi is 3.14159, Pinethicket, Pit, Pizza Puzzle, Plasticup, Pogipogi, Poldi, Polluxian, Polonium,Polyamorph, Poor Yorick, Potatoswatter, Prabash.A, Prashan08, PrincessofLlyr, PrivateMasterHD, Prohlep, Prosfilaes, Protonk, ProvingReliabilty, Pt, Ptyxs, Punctilius, QECUB, Qsq, Quadell,Quebec99, QuentinUK, Quinsareth, Quuxplusone, Qwertyus, R'n'B, R3m0t, R4rtutorials, REggert, RScheiber, Raghavkvp, RainbowOfLight, Rallias, RandyGBrooks, Ravisankarvn, Rbonvall,Rdsmith4, Reach Out to the Truth, ReconditeRodent, RedWolf, Redhanker, Reffyy, Rehabe, Reinderien, Reisio, Remember the dot, RenamedUser01302013, Requestion, Rethnor, RexNL, RichFarmbrough, Richard Simons, Richard24simon, Rijurekh, Ritualizer, Rjbrock, Rjwilmsi, Roadrunner, Robbiemorrison, Robdumas, Robertd, Robo Cop, Rocketrod1960, Rockfang, RodneyMyers,RogueMomen, Rold50, Ronark, Ronhjones, Ronnyim12345, Ronyclau, Root@localhost, Rory O'Kane, Rosive, Rossami, RoySmith, Royote, Rprpriya, Rror, Rszeno, Rtfb, Rursus, Rushbugled13,Ruud Koot, Ruy Pugliesi, Ryan Norton, RyanCross, Ryty01, S2000magician, SJP, STL, Sachin Joseph, Sadday, Sae1962, Saigopalrocks, Saimhe, Salesvery1, Samthedude55, Samuel, SashaSlutsker, Sbisolo, Sbvb, SchfiftyThree, Schiralli, SchnitzelMannGreek, Schumi555, ScoPi, Scoops, Scorp.pankaj, Scott, Scottlemke, Scythe33, SebastianHelm, Sebastiangarth, Sebor, Sentense12,Seraphim, Sergei, Sev2013, Sfxdude, Sg227, Shadowblade0, Shadowjams, Shaurya44, Shawnc, SheffieldSteel, ShellCoder, Shinjiman, Shiv narayan, Shrike, Sidhantx, Sigma 7, Silivrenion,Simetrical, Simon Brady, Simon G Best, SimonP, Simplas, Sinternational, Sirex98, Siripuramrk, Sishgupta, Sitethief, Skew-t, Skizzik, SkyWalker, Sl, Sleep pilot, Sligocki, Slothy13, Smsarmad,Smyth, Snaxe920, Sneftel, Snigbrook, Snowolf, Sohmc, Sokari, Solarra, SomeRandomPerson23, Sommers, Sowsnek, Spaz man, Spiel, Spitfire, SplinterOfChaos, Spokestrip EMP, SpuriousQ,Sra nasir, Stamptrader, Stanthejeep, Startswithj, SteinbDJ, Stephan Schulz, Stephenb, Steve carlson, Steven Zhang, Stevenj, StewartMH, Stheller, Stoni, StoptheDatabaseState, Strangnet, Strcat,Strike Eagle, Stringle, Stuartclift, Style, Suffusion of Yellow, Supertouch, Suppa chuppa, Surfer43, Surv1v4l1st, Sutambe, SvGeloven, Svick, Swalot, Sweecoo, SwisterTwister, Sydius, T,T0pem0, T4bits, TCorp, THEN WHO WAS PHONE?, Tagus, Takis, TakuyaMurata, Tattema, Tbleher, Tbtkorg, TeaDrinker, Technical 13, Technion, Tedickey, Template namespaceinitialisation script, Tero, Tetra HUN, TexMurphy, Tgeairn, Tgrahmann1, The 888th Avatar, The Anome, The Inedible Bulk, The Minister of War, The Nameless, The Thing That Should Not Be,TheDeathCard, TheIncredibleEdibleOompaLoompa, TheMandarin, TheNightFly, TheSuave, TheTim, Theatrus, Thebrid, Theda, Thematrixv, Theopolisme, Theorangepolo, Thiagomael,Thumperward, Tideflat, Tietew, Tifego, Tigerbomb8, Tigrisek, Tim Starling, Tim32, TingChong Ma, Tinus, Titamation, TitaniumCarbide, Titodutta, Tobias Bergemann, Toddlertoddy, Toffile,TomBrown16, TomCat2800, Tomalak geretkal, Tommy2010, Tompsci, Tomshutterbug, Tony Sidaway, Topsfield99, Torc2, Tordek ar, Toshio Yamaguchi, Toussaint, Tpbradbury, Traroth,Trevor MacInnis, TreyHarris, Troels Arvin, Trogdor31, Trusilver, Ts4z, Tslocum, Turdboy3900, Turian, TuukkaH, Ubardak, Umapathy, Umpteee, Unendra, Ungahbunga, Unician,UnicornTapestry, Urhixidur, Urod, UrsaFoot, Useight, Userabc, UtherSRG, Utnapistim, VTPG, Val42, Van fisted, Vanished user 99034jfoiasjq2oirhsf3, Vanished user 9i39j3, Vchimpanzee,Vincenzo.romano, Vinci0008, Viperez15, VladV, Vladimir Bosnjak, Vrenator, Wamiq, Wangi, Waqaee, Wavelength, Wazzup80, Webclient101, Werddemer, Werdna, Westway50, WhaleloverFrost, Who, Wickorama, Widr, WikHead, WikiTerminator1991, Wikidemon, Wikidrone, Wikipendant, Wikiwonky, Willbennett2007, Wilson44691, Winchelsea, Wknight94, Wlievens,Woohookitty, WookieInHeat, Writ Keeper, Wsikard, Wtb435, Wtmitchell, XJaM, Xelnos21, Xerxesnine, Xoaxdotnet, Yamla, Yankees26, Yashykt, Yboord028, Ybungalobill, Ycubed100,Yoshirules367, Ysangkok, Yt95, Yurik, ZacharyM001, Zck, Zed toocool, Zenohockey, Zigmar, Zlog3, Zmwangx, Zoe, Zr2d2, Zrs 12, Zundark, ZungBang, Zvn, Ævar Arnfjörð Bjarmason,ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ, Σ, Александър, ПешСай, Ἀγάπη, 无 名 氏, 2430 anonymous edits

C++ Standard Library  Source: http://en.wikipedia.org/w/index.php?oldid=609437939  Contributors: 1&only, 1exec1, 90 Auto, Abdull, AlexExtreme, Alksentrs, Andonic, Atif.t2, BD2412,Beta16, Bgwhite, Borgx, Celtic Minstrel, Chealer, Chris the speller, Christian75, Comp.arch, CrazyLegsKC, Curps, Decltype, Deryck Chan, Eelis, Figs, Forderud, Fred B. Nurk, Fresheneesz,Geregen2, Giftlite, H3g3m0n, Hdante, Igor the Perfectionist, Inquam, Int19h, Jason Quinn, Jfire, KTC, King of Hearts, LiDaobing, Liao, Ligand, Lir, MK8, MarSch, Martarius, MattGiuca,Mikrosam Akademija 5, Mirror Vax, Momergil, Mrahner, Mrjeff, Mxn, Nbarth, Nichtich, Nick, Pak21, Pedram.salehpoor, Pomte, PuzzletChung, Sae1962, Sebor, Snaxe920, Soumyasch, Spoon!,Steinsky, Subtractive, Suruena, Theclawen, Tim Starling, Timotheus Canens, Trevor Andersen, Uray M. János, Urod, Wikiwonky, Wing gundam, Yshalabi, Zundark, Zvika, Ævar ArnfjörðBjarmason, 76 anonymous edits

Page 55: C++

Article Sources and Contributors 53

Standard Template Library  Source: http://en.wikipedia.org/w/index.php?oldid=602699506  Contributors: 1exec1, A5b, Abdeljalil, Ahannani, Alex.mccarthy, AleyCZ, Alfio, Alksentrs,Alvin-cs, AnOddName, Andres, Andrew Helwer, Aprock, Aragorn2, Atallcostsky, Avinashm, Barfooz, BenFrantzDale, Benhoyt, Bobbyi, Brainfsck, Bwagstaff, CWenger, Chemisor,ChessKnught, Chris-gore, Cibu, Compfreak7, Crasshopper, Cubbi, Curps, DanielKO, David Eppstein, Decltype, Deineka, Demonkoryu, Deryck Chan, Discospinster, Dreftymac, Drrngrvy,Emuka, Enerjazzer, Flex, Forderud, Frecklefoot, Furrykef, Gaius Cornelius, Geregen2, Glenn, GoldenMedian, Gustavo.mori, Hadas583, Happyuk, Hydrogen Iodide, Ian Pitchford, Ipsign, J04n,JTN, Jason Quinn, Jesse Viviano, Jibjibjib, Jjcolotti, Jkt, Jorend, Josh Cherry, Joule36e5, Jyellott, K3rb, Keno, Komap, Kutulu, Lawrencegold, Leushenko, LiDaobing, Lihaas, LilHelpa, Loneboatman, Mankarse, MarSch, Marc Mongenet, Mark Arsten, Martin Moene, Merphant, Milliams, Minghong, Mirror Vax, Mmernex, Modster, Moritz, Mrjeff, Mushroom, Muthudesigner,NapoliRoma, Neilc, Nneonneo, Norm mit, Nwbeeson, Ollydbg, Omnicog, OutlawSipper, Oğuz Ergin, Paercebal, Pavel Senatorov, Pavel Vozenilek, Pedram.salehpoor, Pieleric, Piet Delport,Pomoxis, Pt, Pulseczar, Quietbritishjim, R2100, Rijkbenik, Rjwilmsi, RogueClay, Rookkey, RoySmith, Sae1962, Sairahulreddy, Saziel, ScotXW, Sdorrance, Sebor, Shoaler, Smalljim, Smyth,Soumyasch, Spoon!, Spurrymoses, StasMalyga, Stoph, Strcat, Streetraider, Tacvek, Tavianator, TheGeomaster, Thumperward, TingChong Ma, Tkgauri, Tobias Bergemann, Toffile, TonySidaway, Torc2, Tyler Oderkirk, Uiweo, Vald, Vincenzo.romano, W Nowicki, Whaa?, Wiki0709, Wmbolle, Wolkykim, Xerxesnine, Yoursunny, Zigger, Zundark, Zzuuzz, 172 anonymous edits

C++ Technical Report 1  Source: http://en.wikipedia.org/w/index.php?oldid=609521964  Contributors: Afog, Alvin-cs, BenFrantzDale, Christian75, Coolv, Curps, Cybercobra, Decltype,Drrngrvy, ErikHaugen, Esmith-rowland, Exe, Forderud, Fropuff, Furrykef, Gildos, H3g3m0n, Ivansorokin, JWWalker, Jfmantis, JonKalb, Kjoonlee, Korval, Lhearne, Lowellian, Magioladitis,MarSch, Martarius, Mfwitten, Mirror Vax, Mrjeff, Musiphil, Myork, Nbarth, Nneonneo, Notopia, Odddoe323, Oleg Alexandrov, Pavel Vozenilek, Pedram.salehpoor, Phatom87, Phresnel,Realwhz, Silly rabbit, Skrapion, Soumyasch, Swoög, W.E.Brown, 43 anonymous edits

Boost (C++ libraries)  Source: http://en.wikipedia.org/w/index.php?oldid=603729236  Contributors: 1exec1, Akavel, Aledeniz, Alexey Petrov, AlistairMcMillan, Amenel, Andreas Toth,AnkitGoyal228, Apoc2400, Aranel, ArglebargleIV, Arjun G. Menon, Arw, Asakagi, Axlrosen, BaldPark, Beland, BenFrantzDale, Benhocking, Biboudou, Blaisorblade, Bluemoose, Caiyu,Capricorn42, Chealer, Cogiati, DanielPharos, Daniele de Rigo, Danielstp, Dbenbenn, Decltype, Deineka, Demonkoryu, Dicklyon, Dr. WTF, Dreftymac, Drrngrvy, Dysprosia, Enerjazzer, FFMG,Felipe1982, Forderud, Frap, Fresheneesz, Gennaro Prota, Gioto, Greenscientist, GregorB, Gronky, Gtfjbl, Happyuk, Iceman42, Ilona123, Ipsign, Isilanes, Ivansorokin, Jdavis79, Jerryobject,Jgrahn, JustThisGuy, Jwaustin188, Kate, Kl4m-AWB, Lanzkron, Lexw, LittleDan, Lone boatman, Loqui, Luen, M@RIX, Ma-Lik, Magioladitis, Malaquias, Mark viking, Marqueed, MaximusRex, MichaelGoldshteyn, Mikademus, Mikeblas, Mirror Vax, Msnicki, Nate Silva, Notopia, Nwbeeson, Odin1979, Oleg Alexandrov, Pavel Vozenilek, Pcb21, Pedram.salehpoor, Pjacobi,Ptmc2112, Qwertyus, RJFJR, Raysonho, RedWolf, Rfl, Rhubbarb, Robbiemorrison, RoySmith, Rpyle731, Sanders muc, Savuporo, ScotXW, Sergey shandar, Shuitu, Soumyasch,SparsityProblem, Taeu Yi, The Nut, Thumperward, Tigrisek, Tobias Bergemann, TobiasPersson, Useight, User234234234234, Valery.lesin, Voskanyan, Vu64, Wahwah, Wickorama, WilfriedC,Zarathrustra, Zoicon5, Zondor, Zundark, 이형주, 137 anonymous edits

Const-correctness  Source: http://en.wikipedia.org/w/index.php?oldid=607349552  Contributors: 1&only, Abdull, Alai, Alexey Izbyshev, AnOddName, Axlrosen, Bdesham, BenFrantzDale,Bgwhite, Bluemoose, Btx40, Calvinkrishy, CanisRufus, CesarB, Cybercobra, Czarkoff, Daveohlsson, Derek R Bullamore, Edward, Fbb, Fcmartins, Fewaffles, Ffxi Spot, Flex, Forderud,Furrykef, GregorB, Hvn0413, IamOz, Int19h, JTN, Jarble, Jarry1250, Jengelh, Jess T, Jgrahn, John ch fr, Jonaskahn, Kri, Ljfa-ag, Mahanga, ManoaChild, MarSch, MarkRushakoff, Mbarbier,Mecanismo, Nbarth, Njd27, Now3d, OracleofTroy, OttRider, Phonetagger, Purplefeltangel, Quuxplusone, Rbonvall, Roboshed, Ruakh, Shadowjams, Shawn12341234, Sigra, SimonTrew, SirAnguilla, Smyth, Spiel496, Spoon!, Steveha, TakuyaMurata, TheIncredibleEdibleOompaLoompa, Timphilipw, TomJF, Torc2, Tsunanet, Wbm1058, Wdyoung, Wlievens, XP1, 94 anonymousedits

Virtual function  Source: http://en.wikipedia.org/w/index.php?oldid=617213124  Contributors: .digamma, A Quest For Knowledge, AKEB, Abdull, Achowat, Akihabara, AlexPlank, AndreasKaufmann, Andres Agudelo, Anupamsr, Atlant, Azakhark, Bamgooly, BenFrantzDale, Boai, BrendanSimon, Brownb2, Carolfrog, Catskul, Cedar101, Chaotic Mind, Chei, Chmarkine,Cybercobra, DabMachine, David Levy, Decltype, Dekart, Doug4, DragonLord, EagerToddler39, Emc2, EngineerFromVega, EngineeringDynamo, Eniagrom, Esmond.pitt, Ethanlim, FatalError,Flyer22, Forderud, Fresheneesz, Fæ, Gang65, Gbchaosmaster, Jason Quinn, Jasper Deng, Jenrzzz, Jeremy norbury, Jimw338, Jleedev, Jondel, Kendall-K1, Kostmo, Kznf, LaZ0r, Lanzkron,Liam987, Liao, LieAfterLie, Liss, LoStrangolatore, Mandarax, Marudubshinki, MattGiuca, Meawoppl, Mecanismo, Meitar, Meitme, Mjb, Moggie2002, Mordomo, Muchness, Mud4t, Noldoaran,Noommos, Nxavar, Ogourment, OnionBulb, OutRIAAge, Parleer, Paulexyn0, Polluks, Pooryorick, Qgeissmann, Qwertyus, RHaden, Rentier, S.K., Sae1962, Sallushan, Shawn wiki, Simetrical,Snaxe920, Spoon!, Sun Creator, Tadanisakari, Takeshita kenji, Takua108, Taral.shah, Tarun123v, Techman224, Tobias Bergemann, Topbanana, Trainsonplanes, UberCryxic, Urhixidur, Vnv lain,Who, WookieInHeat, Wtmitchell, Yuanyelele, Zemyla, Zhangsu, Ztobor, 309 anonymous edits

Template (C++)  Source: http://en.wikipedia.org/w/index.php?oldid=615469326  Contributors: 12.21.224.xxx, 166.82.201.xxx, 5 albert square, AMackenzie, Abdull, AdiJapan, Aks.abhishek,Alexey Muranov, Alxeedo, AnantharamNV, Bakkedal, BevinBrett, Blackmage71, Brianbjparker, Cetinsert, Cic, Compy 386, Conversion script, Crasshopper, Davehi1, Daydreamer302000,Decltype, Dekart, Der Messer, Derek Ross, Dougmoby, Dreftymac, Dysprosia, Eequor, Fender0107401, Foolip, Fraxtil, Fulax, GiM, Gildos, Graham87, Hvn0413, Jjdawson7, John of Reading,Jonhanson, Jorend, Jtdunlop, Kostmo, Latios, LinXitoW, Litb me, LoStrangolatore, Magnus.de, Markuswp, Martyn Lovell, MaskedHero, Mef526, Michael miceli, Mikemoral, Miqademus, Mirv,Modify, Modster, MoorTnelis, MusicScience, Naohiro19, Nneonneo, Ojw, Phorgan1, Pnm, RokerHRO, Ronz, Sassf, Sodium, Spizella, SteveBaker, Suffusion of Yellow, TakuyaMurata, Tarquin,Thecheesykid, Thumperward, Tobias Bergemann, Torc2, Tzler, Vald, Velella, Velowiki, Wickorama, Wikidrone, WiseWoman, Wootery, Xchmelmilos, Xompanthy, Yamla, Ykhwong, Zundark,127 anonymous edits

Page 56: C++

Image Sources, Licenses and Contributors 54

Image Sources, Licenses and Contributorsfile:Wikibooks-logo-en-noslogan.svg  Source: http://en.wikipedia.org/w/index.php?title=File:Wikibooks-logo-en-noslogan.svg  License: Creative Commons Attribution-Sharealike 3.0 Contributors: User:Bastique, User:Ramac et al.File:BjarneStroustrup.jpg  Source: http://en.wikipedia.org/w/index.php?title=File:BjarneStroustrup.jpg  License: GNU Free Documentation License  Contributors: -Image:Wikibooks-logo-en-noslogan.svg  Source: http://en.wikipedia.org/w/index.php?title=File:Wikibooks-logo-en-noslogan.svg  License: Creative Commons Attribution-Sharealike 3.0 Contributors: User:Bastique, User:Ramac et al.File:Boost.png  Source: http://en.wikipedia.org/w/index.php?title=File:Boost.png  License: unknown  Contributors: Zoltan JuhaszImage:ClassDiagram for VirtualFunction.png  Source: http://en.wikipedia.org/w/index.php?title=File:ClassDiagram_for_VirtualFunction.png  License: Public Domain  Contributors:OnionBulb

Page 57: C++

License 55

LicenseCreative Commons Attribution-Share Alike 3.0//creativecommons.org/licenses/by-sa/3.0/