You are on page 1of 57

C++

All about 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

Contents
Articles
C++

C++ Standard Library

13

Standard Template Library

18

C++ Technical Report 1

25

Boost (C++ libraries)

32

Const-correctness

34

Virtual function

43

Template (C++)

46

References
Article Sources and Contributors

52

Image Sources, Licenses and Contributors

54

Article Licenses
License

55

C++

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 and
generic 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), with
performance, efficiency and flexibility of use as its design requirements. C++ has also been found useful in many
other contexts, including desktop applications, servers (e.g. e-commerce, web search, SQL), performance critical
applications (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 provide
them, 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 as
C++11). The C++ programming language was initially standardised in 1998 as ISO/IEC 14882:1998, which was
then amended by the C++03, ISO/IEC 14882:2003, standard. The current standard (C++11) supersedes these, with
new features and an enlarged standard library.
Before standardization (1989 onwards), C++ was developed by Bjarne Stroustrup at Bell Labs, starting in 1979, who
wanted 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).

C++

History
Bjarne Stroustrup, a Danish and British trained computer scientist,
began his work on C++'s predecessor "C with Classes" in 1979. The
motivation for creating a new language originated from Stroustrup's
experience in programming for his Ph.D. thesis. Stroustrup found that
Simula had features that were very helpful for large software
development, but the language was too slow for practical use, while
BCPL was fast but too low-level to be suitable for large software
development. When Stroustrup started working in AT&T Bell Labs, he
had the problem of analyzing the UNIX kernel with respect to
Bjarne Stroustrup, creator of C++
distributed computing. Remembering his Ph.D. experience, Stroustrup
set 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, other
languages 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 via
Stroustrup'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 were
added including virtual functions, function name and operator overloading, references, constants, type-safe free-store
memory allocation (new/delete), improved type checking, and BCPL style single-line comments with two forward
slashes (//), 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 reference
for the language, as there was not yet an official standard. The first commercial implementation of C++ was released
in 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 basis
for the future standard. Late feature additions included templates, exceptions, namespaces, new casts, and a boolean
type.
In 2011, C++11 was released which added more features and enlarged the standard library further (compared to it in
1998), providing more facilities for C++ programmers to use, with more additions planned for 2014 and 2017.

Etymology
According to Stroustrup: "the name signifies the evolutionary nature of the changes from C". This name is credited
to 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 a
tongue-in-cheek spirit. The name stems from C's "++" operator (which increments the value of a variable) and a
common naming convention of using "+" to indicate an enhanced computer program. A joke goes that the name
itself has a bug: due to the use of post-increment, which increments the value of the variable but evaluates to the
unincremented value, so C++ is no better than C, and the pre-increment ++C form should have been used instead, so
that C++ is better than C.
During C++'s development period, the language had been referred to as "new C", then "C with Classes", before
acquiring its final name.

C++

Philosophy
Throughout C++'s life, its development and evolution has been informally governed by a set of rules that its
evolution 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++ released
and 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 then
published a new version of the C++ standard, ISO/IEC 14882:2003, which fixed problems which had been identified
in C++98.
In 2005, a technical report, called the "Library Technical Report 1" (TR1), was released. While not an official part of
the standard, it specified a number of extensions to the standard library, which were then included in the next version
of C++ (then C++0x).
The latest major revision of the C++ standard, C++11 (formerly known as C++0x), was approved and released on the
12 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 is
planned 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.

C++

Language
C++ inherits most of C's syntax. The following is Bjarne Stroustrup's version of the Hello world program that uses
the 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 the
function results in undefined behaviour (compilers typically provide the means to issue a diagnostic in such a
case).[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, logical
operations and others. Almost all operators can be overloaded for user-defined types, with a few notable exceptions
such as member access (. and .*) as well as the conditional operator. The rich set of overloadable operators is
central to using user created types in C++ as well and as easily as built in types (so that the user using them cannot
tell the difference). The overloadable operators are also an essential part of many advanced C++ programming
techniques, such as smart pointers. Overloading an operator does not change the precedence of calculations
involving the operator, nor does it change the number of operands that the operator uses (any operand may however
be ignored by the operator, though it will be evaluated prior to execution). Overloaded "&&" and "||" operators lose
their short-circuit evaluation property.

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

Static storage duration objects


Thread storage duration objects
Automatic storage duration objects
Dynamic storage duration objects

C++

5
Static storage duration objects
Static storage duration objects are created before main() (see exceptions below) is entered and destroyed in reverse
order of creation after main() exits. The exact order of creation is not specified by the standard (though there are
some rules defined below) to allow implementations some freedom in how to organize there implementation. More
formally, 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 after
all 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 not
specified in the standard this phase can be completed at compile time and saved in the data partition of the
executable.
Dynamic initialization all object initialization that is done via a constructor or function call (unless the function
is marked constexpr C++11). The dynamic initialization order is defined as the order of declaration within the
compilation unit (ie the same file). No guarantees about the order of initialization between compilation units is
provided.
Static members of a class. These are no different from file scope static variables in terms of lifespan (The major
difference 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 is
just 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 the
reverse 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 constructor
or initializer this is used to define the initial state of the object. Local variables are destroyed when the local block or
function 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 last
member of the array in order. Member variables are destroyed when the parent object is destroyed in the reverse
order of creation. i.e. If the parent is an "automatic object" then it will be destroyed when it goes out of scope which
triggers the destruction of all its members.
Temporary variables are created as the result of expression evaluation and are destroyed when the statement
containing the expression has been fully evaluated (usually at the ';' at the end of the statement).

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]

Templates
See also: Template metaprogramming and Generic programming
C++ templates enable generic programming. C++ supports both function and class templates. Templates may be
parameterized by types, compile-time constants, and other templates. Templates are implemented by instantiation at
compile-time. To instantiate a template, compilers substitute specific arguments for a template's parameters to
generate a concrete function or class instance. Some substitutions are not possible; these are eliminated by an
overload resolution policy described by the phrase "Substitution failure is not an error" (SFINAE). Templates are a
powerful tool that can be used for generic programming, template metaprogramming, and code optimization, but this
power implies a cost. Template use may increase code size, because each template instantiation produces a copy of
the template code: one for each set of template arguments, however, this is the same amount of code that would be
generated, or less, that if the code was written by hand. This is in contrast to run-time generics seen in other
languages (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 conditional
compilation, templates are not restricted to lexical substitution. Templates are aware of the semantics and type
system of their companion language, as well as all compile-time type definitions, and can perform high-level
operations including programmatic flow control based on evaluation of strictly type-checked parameters. Macros are
capable 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 and
text-inclusion/exclusion. In other words, macros can control compilation flow based on pre-defined symbols but
cannot, unlike templates, independently instantiate new symbols. Templates are a tool for static polymorphism (see
below) and generic programming.
In addition, templates are a compile time mechanism in C++ that is Turing-complete, meaning that any computation
expressible 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 specific
arguments used to instantiate it. After instantiation, the resulting code is equivalent to code written specifically for
the passed arguments. In this manner, templates provide a way to decouple generic, broadly applicable aspects of
functions and classes (encoded in templates) from specific aspects (encoded in template parameters) without
sacrificing performance due to abstraction.

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

C++

7
Encapsulation
Encapsulation is the hiding of information to ensure that data structures and operators are used as intended and to
make the usage model more obvious to the developer. C++ provides the ability to define classes and functions as its
primary encapsulation mechanisms. Within a class, members can be declared as either public, protected, or private to
explicitly enforce encapsulation. A public member of the class is accessible to any function. A private member is
accessible only to functions that are members of that class and to functions and classes explicitly granted access
permission by the class ("friends"). A protected member is accessible to members of classes that inherit from the
class 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 type
should 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 is
allowed to make public entities that are not part of the representation of the type. Therefore, C++ supports not just
OO 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 functions
that are part of a minimal interface for users of the class. This can hide the details of data implementation, allowing
the 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 be
declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can
access the inherited public and protected members of the base class. Only public inheritance corresponds to what is
usually 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 called
virtual 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 more
than one base class; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can
inherit from both "Cat" and "Flying Mammal". Some other languages, such as C# or Java, accomplish something
similar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of base
classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or
member 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 normally
explicitly defined in the derived class, not inherited implicitly. C++ virtual inheritance exhibits an ambiguity
resolution feature called dominance.

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

C++

8
Static polymorphism
Function overloading allows programs to declare multiple functions having the same name (but with different
arguments). The functions are distinguished by the number or types of their formal parameters. Thus, the same
function name can refer to different functions depending on the context in which it is used. The type returned by the
function 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 allows
the parameters with defaults to optionally be omitted when the function is called, in which case the default
arguments will be used. When a function is called with fewer arguments than there are declared parameters, explicit
arguments are matched to parameters in left-to-right order, with any unmatched parameters at the end of the
parameter list being assigned their default arguments. In many cases, specifying default arguments in a single
function 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, through
the Curiously Recurring Template Pattern, it's possible to implement a form of static polymorphism that closely
mimics the syntax for overriding virtual functions. Because C++ templates are type-aware and Turing-complete, they
can also be used to let the compiler resolve recursive conditionals and generate substantial programs through
template metaprogramming. Contrary to some opinion, template code will not generate a bulk code after compilation
with 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 type
in addition to objects exactly matching the variable type. This allows arrays and other kinds of containers to hold
pointers to objects of differing types. Because assignment of values to variables usually occurs at run-time, this is
necessarily a run-time phenomenon.
C++ also provides a dynamic_cast operator, which allows the program to safely attempt conversion of an object
into an object of a more specific object type (as opposed to conversion to a more general type, which is always
allowed). This feature relies on run-time type information (RTTI). Objects known to be of a certain specific type can
also be cast to that type with static_cast, a purely compile-time construct that has no runtime overhead and
does 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 determined
by the type of the object. A given function is overridden when there exists no difference in the number or type of
parameters between two or more definitions of that function. Hence, at compile time, it may not be possible to
determine the type of the object and therefore the correct function to call, given only a base class pointer; the
decision is therefore put off until runtime. This is called dynamic dispatch. Virtual member functions or methods
allow the most specific implementation of the function to be called, according to the actual run-time type of the
object. In C++ implementations, this is commonly done using virtual function tables. If the object type is known, this
may be bypassed by prepending a fully qualified class name before the function call, but in general calls to virtual
functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can be virtual. A general rule of thumb
is that if any functions in the class are virtual, the destructor should be as well. As the type of an object at its creation
is known at compile time, constructors, and by extension copy constructors, cannot be virtual. Nonetheless a
situation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as a
pointer to a base object. In such a case, a common solution is to create a clone() (or similar) virtual function that
creates and returns a copy of the derived class when called.

C++

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

Exception handling
Exception handling is a mechanism in C++ that is used to handle errors in a uniform manner and separately from the
main body of a programme's source code. Should an error occur, an exception is thrown (raised), which is then
caught by an exception handler. The code that might cause an exception to be thrown goes in a try block (is
enclosed 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 all
exceptions. As all the standard library exceptions have std::exception as their base class, catching
std::exception will catch all standard library exceptions. As is shown above (e.what()), all exceptions that
derive 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 library
The C++ standard consists of two parts: the core language and the C++ Standard Library; which C++ programmers
expect 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; reading
from the console input, reading/writing from files), smart pointers for automatic memory management, regular
expression support, multi-threading library, atomics support (allowing a variable to be read or written to be at most
one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a
system for converting error reporting that doesn't use C++ exceptions into C++ exceptions, a random number
generator 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

C++

10
compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any
container 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 generic
algorithms and containers for many years. When he started with C++, he finally found a language where it was
possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard
library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The
standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to
distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C
library subset, etc.).
Most C++ compilers, and all major ones, provide a standards conforming implementation of the C++ standard
library.

Compatibility
Producing a reasonably standards-compliant C++ compiler has proven to be a difficult task for compiler vendors in
general. For many years, different C++ compilers implemented the C++ language to different levels of compliance to
the standard, and their implementations varied widely in some areas such as partial template specialization. Recent
releases 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 implementation
of name mangling, exception handling, and other implementation-specific features. The downside of this decision is
that object code produced by different compilers is expected to be incompatible. There were, however, attempts to
standardize compilers for particular machines or operating systems (for example C++ ABI), though they seem to be
largely abandoned now.

With C
For 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 compile
correctly in C++, but there are a few differences that cause some valid C code to be invalid or behave differently in
C++. For example, C allows implicit conversion from void* to other pointer types, but C++ does not (for type
safety 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 number
of 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++ it
is a fundamental type) and the restrict keyword. Some of the C99-introduced features were included in the
subsequent 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 may
not rely on features depending on name mangling (i.e., function overloading).

C++

11

References
[1]
[2]
[3]
[4]
[5]
[6]

http:/ / isocpp. org/


Bjarne Stroustrup - HOPL-II paper
Bjarne Stroustrup - HOPL-II paper (http:/ / www. stroustrup. com/ hopl2. pdf)
ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages C++ 6.6.3 The return statement [stmt.return] para. 2
ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages C++ 3.6.1 Main function [basic.start.main] para. 5
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. ISBN0-321-22725-5.
Alexandrescu, Andrei (2001). Modern C++ Design: Generic Programming and Design Patterns Applied.
Addison-Wesley. ISBN0-201-70431-5.
Alexandrescu, Andrei; Sutter, Herb (2004). C++ Design and Coding Standards: Rules and Guidelines for
Writing Programs. Addison-Wesley. ISBN0-321-11358-6.
Becker, Pete (2006). The C++ Standard Library Extensions : A Tutorial and Reference. Addison-Wesley.
ISBN0-321-41299-0.
Brokken, Frank (2010). C++ Annotations (http://www.icce.rug.nl/documents/cplusplus/). University of
Groningen. ISBN90-367-0470-7.
Coplien, James O. (1992, reprinted with corrections 1994). Advanced C++: Programming Styles and Idioms.
ISBN0-201-54855-0.
Dewhurst, Stephen C. (2005). C++ Common Knowledge: Essential Intermediate Programming. Addison-Wesley.
ISBN0-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.
ISBN0-321-62321-5.
Koenig, Andrew; Moo, Barbara E. (2000). Accelerated C++ Practical Programming by Example.
Addison-Wesley. ISBN0-201-70353-X.
Lippman, Stanley B.; Lajoie, Jose; Moo, Barbara E. (2011). C++ Primer (Fifth ed.). Addison-Wesley.
ISBN0-470-93244-9.
Lippman, Stanley B. (1996). Inside the C++ Object Model. Addison-Wesley. ISBN0-201-83454-5.
Meyers, Scott (2005). Effective C++ (Third ed.). Addison-Wesley. ISBN0-321-33487-6.
Stroustrup, Bjarne (2000). The C++ Programming Language (Special ed.). Addison-Wesley.
ISBN0-201-70073-5.
Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley. ISBN0-201-54330-3.

C++

12
Stroustrup, Bjarne (2009). Programming Principles and Practice Using C++. Addison-Wesley.
ISBN0-321-54372-6.
Sutter, Herb (2001). More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and
Solutions. Addison-Wesley. ISBN0-201-70434-X.
Sutter, Herb (2004). Exceptional C++ Style. Addison-Wesley. ISBN0-201-76042-8.
Vandevoorde, David; Josuttis, Nicolai M. (2003). C++ Templates: The complete Guide. Addison-Wesley.
ISBN0-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 Working


Group

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 (19912006) (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 with
Bjarne 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 and
understanding of standard C++. Bjarne Stroustrup is a director of the organization.

C++ Standard Library

13

C++ Standard Library


In the C++ programming language, the C++ Standard Library is a collection of classes and functions, which are
written in the core language and part of the C++ ISO Standard itself.[1] The C++ Standard Library provides several
generic 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 as
finding the square root of a number. The C++ Standard Library also incorporates 18 headers of the ISO C90 C
standard 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 has
been influenced by research in generic programming and developers of the STL such as Alexander Stepanov and
Meng Lee. Although the C++ Standard Library and the STL share many features, neither is a strict superset of the
other.
A noteworthy feature of the C++ Standard Library is that it not only specifies the syntax and semantics of generic
algorithms, but also places requirements on their performance.[3] These performance requirements often correspond
to a well-known algorithm, which is expected but not required to be used. In most cases this requires linear time
O(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 was
introduced to allow both fast average performance and optimal worst-case complexity, and as of C++11, sorting is
guaranteed to be at worst linearithmic. In other cases requirements remain laxer, such as selection, which is only
required 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 is
undergoing further work regarding standardization of expanded functionality.

C++ Standard
Library

Input/output
Strings
Standard Template Library

algorithm

functional

iterator

Sequence containers

Associative containers

Unordered associative containers


C standard library

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 headers
The 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 sized
array.
<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 and
multimap.
<queue>
Provides the container adapter class std::queue, a single-ended queue, and std::priority_queue, a
priority queue.
<set>
Provides the container class templates std::set and std::multiset, sorted associative containers or
sets.
<stack>

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
std::unordered_multimap, hash tables.

and

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

and

<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, and
clocks.
<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, both
derived 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 the
namespace 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>

C++ Standard Library


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 the
precision 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 files
or strings.

Language support
<exception>
Provides several types and functions related to exception handling, including std::exception, the base
class of all exceptions thrown by the Standard Library.
<limits>
Provides the template class std::numeric_limits, used for describing properties of fundamental
numeric 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.

16

C++ Standard Library

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 until
notified 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 library
Components that C++ programs may use to perform seminumerical operations.
<complex>
The header <complex> defines a class template, and numerous functions for representing and manipulating
complex 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 library
Main article: C Standard Library
Each header from the C Standard Library is included in the C++ Standard Library under a different name, generated
by removing the .h, and adding a 'c' at the start; for example, 'time.h' becomes 'ctime'. The only difference between
these headers and the traditional C Standard Library headers is that where possible the functions should be placed
into the std:: namespace. In ISO C, functions in the standard library are allowed to be implemented by macros, which
is not allowed by ISO C++.

17

C++ Standard Library

18

References
[1]
[2]
[3]
[4]
[5]

ISO/IEC 14882:2003(E) Programming Languages C++ 17-27


ISO/IEC 14882:2003(E) Programming Languages C++ D.5
" Generic Algorithms (http:/ / www. cs. rpi. edu/ ~musser/ gp/ algorithms. html)", David Musser
nth_element (http:/ / en. cppreference. com/ w/ cpp/ algorithm/ nth_element)
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++ Standard
Library

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>

Standard Template Library

19

v
t

e [5]

The Standard Template Library (STL) is a software library for the C++ programming language that influenced
many parts of the C++ Standard Library. It provides four components called algorithms, containers, functional, and
iterators.
The STL provides a ready-made set of common classes for C++, such as containers and associative arrays, that can
be used with any built-in type and with any user-defined type that supports some elementary operations (such as
copying and assignment). STL algorithms are independent of containers, which significantly reduces the complexity
of the library.
The STL achieves its results through the use of templates. This approach provides compile-time polymorphism that
is often more efficient than traditional run-time polymorphism. Modern C++ compilers are tuned to minimize any
abstraction 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 value
semantics.

Composition
Containers
The STL contains sequence containers and associative containers. The standard sequence containers include
vector , deque , and list . The standard associative containers are set , multiset , map , and
multimap . There are also container adaptorsqueue , priority_queue , and stack , that are containers
with 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 map
or hash_map (described below) are of type 'pair' by default, where all the 'first' elements act as the unique keys, each
associated 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 inserting
or erasing an object. Inserting and removing an element to/from back of the vector at the end takes amortized constant
time. Inserting and erasing at the beginning or in the middle is linear in time. A specialization for type bool exists, which
optimizes 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 lookup
and access (linear time), but once a position has been found, quick insertion and deletion (constant time).

deque (double-ended
queue)

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

queue

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

Standard Template Library

priority queue

20

Provides priority queue interface in terms of push/pop/top operations (the element with the highest priority is
on top). Any random-access sequence supporting operations front() , push_back() , and
pop_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 popped
first).

stack

Provides LIFO stack interface in terms of push/pop/top operations (the last-inserted element is on top). Any
sequence supporting operations back() , push_back() , and pop_back() can be used to instantiate
stack (e.g. vector , list , and deque ).
Associative containers: unordered collections

set

multiset
map

multimap
unordered_set
unordered_multiset
unordered_map
unordered_multimap

a mathematical set; inserting/erasing elements in a set does not invalidate iterators pointing in the set. Provides set
operations union, intersection, difference, symmetric difference and test of inclusion. Type of data must implement
comparison operator < or custom comparator function must be specified; such comparison operator or comparator
function must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using a
self-balancing binary search tree.
same as a set, but allows duplicate elements (mathematical Multiset).
an associative array; allows mapping from one data item (a key) to another (a value). Type of key must implement
comparison operator < or custom comparator function must be specified; such comparison operator or comparator
function must guarantee strict weak ordering, otherwise behavior is undefined. Typically implemented using a
self-balancing binary search tree.
same as a map, but allows duplicate keys.
similar to a set, multiset, map, or multimap, respectively, but implemented using a hash table; keys are not ordered, but a
hash function must exist for the key type. These containers are part of C++11.

Other types of containers


bitset

valarray

stores series of bits similar to a fixed-sized vector of bools. Implements bitwise operations and lacks iterators. Not a
Sequence.
another C-like array like vector, but is designed for high speed numerics at the expense of some programming ease and
general purpose use. It has many features that make it ideally suited for use with vector processors in traditional vector
supercomputers and SIMD units in consumer-level scalar processors, and also ease vector mathematics programming
even in scalar computers.

Iterators
The STL implements five different types of iterators. These are input iterators (that can only be used to read a
sequence of values), output iterators (that can only be used to write a sequence of values), forward iterators (that can
be read, written to, and move forward), bidirectional iterators (that are like forward iterators, but can also move
backwards) 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 be
done by simply moving forward a step at a time a total of ten times. However, having distinct random access
iterators offers efficiency advantages. For example, a vector would have a random access iterator, but a list only a
bidirectional iterator.
Iterators are the major feature that allow the generality of the STL. For example, an algorithm to reverse a sequence
can be implemented using bidirectional iterators, and then the same implementation can be used on lists, vectors and
deques. User-created containers only have to provide an iterator that implements one of the five standard iterator
interfaces, 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

Standard Template Library


opaque to algorithms using iterators.

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

Functors
The STL includes classes that overload the function call operator (operator() ). Instances of such classes are
called 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 state
information along with the function. Since both functors and function pointers can be invoked using the syntax of a
function call, they are interchangeable as arguments to templates when the corresponding parameter only appears in
function call contexts.
A particularly common type of functor is the predicate. For example, algorithms like find_if take a unary
predicate that operates on the elements of a sequence. Algorithms like sort, partial_sort, nth_element and all sorted
containers use a binary predicate that must provide a strict weak ordering, that is, it must behave like a membership
test on a transitive, non reflexive and asymmetric binary relation. If none is supplied, these algorithms and containers
use less [1] by default, which in turn calls the less-than-operator <.

History
The architecture of STL is largely the creation of Alexander Stepanov. In 1979 he began working out his initial ideas
of generic programming and exploring their potential for revolutionizing software development. Although David
Musser had developed and advocated some aspects of generic programming already by year 1971, it was limited to a
rather specialized area of software development (computer algebra).
Stepanov recognized the full potential for generic programming and persuaded his then-colleagues at General
Electric Research and Development (including, primarily, David Musser and Deepak Kapur) that generic
programming should be pursued as a comprehensive basis for software development. At the time there was no real
support 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. In
1985, the Eiffel programming language became the first object-oriented language to include intrinsic support for
generic classes, combined with the object-oriented notion of inheritance.[2] By 1987 Stepanov and Musser had
developed and published an Ada library for list processing that embodied the results of much of their research on
generic 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 the
language was relatively immature. Another reason for turning to C++, which Stepanov recognized early on, was the
C/C++ model of computation that allows very flexible access to storage via pointers, which is crucial to achieving
generality without losing efficiency.
Much research and experimentation were needed, not just to develop individual components, but to develop an
overall architecture for a component library based on generic programming. First at AT&T Bell Laboratories and
later at Hewlett-Packard Research Labs (HP), Stepanov experimented with many architectural and algorithm
formulations, first in C and later in C++. Musser collaborated in this research and in 1992 Meng Lee joined
Stepanov'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

21

Standard Template Library


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 a
formal proposal in time for the March 1994 meeting. Despite the tremendous time pressure, Alex and Meng were
able 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 of
committee members met with Stepanov and Lee to help work out the details. The requirements for the most
significant extension (associative containers) had to be shown to be consistent by fully implementing them, a task
Stepanov delegated to Musser. Stepanov and Lee produced a proposal that received final approval at the July 1994
ANSI/ISO committee meeting. (Additional details of this history can be found in Stevens.) Subsequently, the
Stepanov and Lee document 17 was incorporated into the ANSI/ISO C++ draft standard (1, parts of clauses 17
through 27). It also influenced other parts of the C++ Standard Library, such as the string facilities, and some of the
previously 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 into
actual availability and use. With the STL requirements part of the publicly available draft standard, compiler vendors
and independent software library vendors could of course develop their own implementations and market them as
separate products or as selling points for their other wares. One of the first edition's authors, Atul Saini, was among
the first to recognize the commercial potential and began exploring it as a line of business for his company, Modena
Software 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's
decision to make its implementation freely available on the Internet in August 1994. This implementation, developed
by Stepanov, Lee, and Musser during the standardization process, became the basis of many implementations offered
by compiler and library vendors today.

Criticisms
Quality of implementation of C++ compilers
The Quality of Implementation (QoI) of the C++ compiler has a large impact on usability of STL (and templated
code 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 error
messages to make them more comprehensible.
Careless use of STL templates can lead to code bloat.Wikipedia:Citation needed This has been countered with
special techniques within STL implementation (using void* containers internally) and by improving optimization
techniques used by compilers. This is similar to carelessly just copying a whole set of C library functions to work
with a different type.
Template instantiation tends to increase compilation time and memory usage (even by an order of
magnitude)Wikipedia:Citation needed. Until the compiler technology improves enough, this problem can be only
partially eliminated by very careful coding and avoiding certain idioms.

22

Standard Template Library

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. A
similar problem exists in other languages, for example Java. Ranges have been proposed as a safer, more flexible
alternative to iterators.
Certain iteration patterns do not map to the STL iterator model.Wikipedia:Citation needed For example, callback
enumeration APIs cannot be made to fit the STL model without the use of coroutines, which are
platform-dependent or unavailable, and are outside the C++ standard.
Compiler compliance does not guarantee that Allocator objects, used for memory management for containers, will
work with state-dependent behavior. For example, a portable library can't define an allocator type that will pull
memory 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 been
added 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 have
been 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].

23

Standard Template Library

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.
ISBN0-201-37926-0.
Scott Meyers (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library.
Addison-Wesley. ISBN0-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-Wesley
Professional. ISBN0-201-73484-2.
Atul Saini and David R. Musser, STL Tutorial and Reference Guide: C+ + Programming with the Standard
Template Library. Foreword by Alexander Stepanov; [Copyright Modena Software Inc.] Addison-Wesley ISBN
0-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)

24

C++ Technical Report 1

25

C++ Technical Report 1


C++ Technical Report 1 (TR1) is the common name for ISO/IEC TR 19768, C++ Library Extensions, which was
a document proposing additions to the C++ standard library for the C++03 language standard. The additions include
regular expressions, smart pointers, hash tables, and random number generators. TR1 was not a standard itself, but
rather a draft document. However, most of its proposals became part of the current official standard, C++11. Before
C++11 was standardized, vendors used this document as a guide to create extensions. The report's goal was "to build
more 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
published in 2007 as an ISO/IEC standard as ISO/IEC TR 19768:2007 [2].

[1]

, then

Overview
Compilers needed not include the TR1 components to be conforming to the C++ standard, because TR1 proposals
were not part of the standard itself, but only a set of possible additions that were still to be ratified. However, most of
it 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. For
example, 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 standard
library.
There is also a second technical report, C++ Technical Report 2, planned for publishing after C++11 [3].

Components
TR1 includes the following components:

General utilities
Reference wrapper enables passing references, rather than copies, into algorithms or function objects. The feature
was based on Boost.Ref.[4] A wrapper reference is obtained from an instance of the template class
reference_wrapper. Wrapper references are similar to normal references (&) of the C++ language. To obtain
a 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 a
reference (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()
{

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 main
classes are added:
shared_ptr a reference-counted smart pointer
weak_ptr a variant of shared_ptr that doesn't increase the reference count
The proposal is based on Boost Smart Pointer library [5]

Function objects
These four modules are added to the <functional> header file:
Polymorphic function wrapper (function) can store any callable function (function pointers, member
function pointers, and function objects) that uses a specified function call signature. The type does not depend on the
kind of the callable used. Based on Boost.Function [6]
Function object binders (bind) can bind any parameter parameters to function objects. Function composition is
also 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 member
functions to be treated as function objects. Based on Boost Mem Fn library [8]

Metaprogramming and type traits


There 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 on
and 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, and
probability distributions

C++ Technical Report 1

27

Mathematical special functions


Some features of TR1, such as the mathematical special functions and certain C99 additions, are not included
in the Visual C++ implementation of TR1. The Mathematical special functions library was not standardized in
C++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

Function
prototype

Associated
Laguerre
polynomials

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

Associated
Legendre
polynomials

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

Beta function

double beta(
double x, double y
);

Complete elliptic double


integral of the first comp_ellint_1(
kind
double k ) ;
Complete elliptic
integral of the
second kind

double
comp_ellint_2(
double k ) ;

Complete elliptic
integral of the
third kind

double
comp_ellint_3(
double k, double
nu ) ;

Confluent
hypergeometric
functions

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

Regular modified
cylindrical Bessel
functions

double
cyl_bessel_i(
double nu, double
x);

Cylindrical Bessel
functions of the
first kind

double
cyl_bessel_j(
double nu, double
x);

Irregular modified double


cylindrical Bessel cyl_bessel_k(
functions
double nu, double
x);

Mathematical expression

C++ Technical Report 1

Cylindrical
Neumann functions
Cylindrical Bessel
functions of the
second kind

double
cyl_neumann(
double nu, double
x);

Incomplete elliptic double ellint_1(


integral of the first double k, double
kind
phi ) ;
Incomplete elliptic double ellint_2(
integral of the
double k, double
second kind
phi ) ;
Incomplete elliptic double ellint_3(
integral of the
double k, double
third kind
nu, double phi ) ;
Exponential
integral

double expint(
double x ) ;

Hermite
polynomials

double hermite(
unsigned n, double
x);

Hypergeometric
series

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

Laguerre
polynomials

double laguerre(
unsigned n, double
x);

Legendre
polynomials

double legendre(
unsigned l, double
x);

Riemann zeta
function

Spherical Bessel
functions of the
first kind

double
riemann_zeta(
double x ) ;

double
sph_bessel(
unsigned n, double
x);

Spherical
double
associated
sph_legendre(
Legendre functions unsigned l,
unsigned m,
double theta ) ;
Spherical
Neumann functions
Spherical Bessel
functions of the
second kind

double
sph_neumann(
unsigned n, double
x);

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

28

C++ Technical Report 1


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, and
unordered_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 standard
library 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 compatibility
C++ is designed to be compatible with the C programming language, but is not a strict superset of C due to diverging
standards. 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 C99
version of the C standard (not all parts of C99 are included in TR1).

29

C++ Technical Report 1

Technical Report 2
In 2005 a request for proposals for a TR2 was made with a special interest in Unicode, XML/HTML, Networking
and 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, instead
enhancements to C++ will be published in a number of Technical Specifications. Some of the proposals listed above
are 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

30

C++ Technical Report 1

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. ISBN0-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.

31

Boost (C++ libraries)

32

Boost (C++ libraries)


Boost

Boost logo
Stable release

1.55.0 / November11, 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 as
linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unit
testing. 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 with
both free and proprietary software projects. Many of Boost's founders are on the C++ standards committee, and
several Boost libraries have been accepted for incorporation into both Technical Report 1 and the C++11 standard.

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

Boost (C++ libraries)

33

Associated people
Original founders of Boost still active in the community include Beman Dawes and David Abrahams. Author of
several books on C++, Nicolai Josuttis contributed the Boost array library in 2001. There are mailing lists devoted to
Boost 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. ISBN978-94-91028-01-4.
Demming, Robert & Duffy, Daniel J. (2012). Introduction to the Boost C++ Libraries. Volume 2 - Advanced
Libraries. Datasim. ISBN978-94-91028-02-1.
Karlsson, Bjrn (2005). Beyond the C++ Standard Library: An Introduction to Boost. Addison-Wesley.
ISBN978-0-321-13354-0.
Polukhin, Antony (2013). Boost C++ Application Development Cookbook. Packt. ISBN978-1-84951-488-0.
Schling, Boris (2011). The Boost C++ Libraries. XML Press. ISBN978-0-9822191-9-5.
Siek, Jeremy G.; Lee, Lie-Quan & Lumsdaine, Andrew (2001). The Boost Graph Library: User Guide and
Reference Manual. Addison-Wesley. ISBN978-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

Const-correctness

34

Const-correctness
In computer programming, const-correctness is the form of program correctness that deals with the proper
declaration of variables or objects as mutable or immutable. The term is mostly used in a C or C++ context, and
takes 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 can
do. Note, however, that in the case of predefined data (such as const char * string literals), C const is often
unwritable.
In addition, a (non-static) member-function can be declared as const. In this case, the this pointer inside such a
function is of type return_value_type const * const rather than merely of type
return_value_type * const. This means that non-const functions for this object cannot be called from
inside such a function, nor can member variables be modified. In C++, a member variable can be declared as
mutable, indicating that this restriction does not apply to it. In some cases, this can be useful, for example with
caching, reference counting, and data synchronization. In these cases, the logical meaning (state) of the object is
unchanged, but the object is not physically constant since its bitwise representation may change.

C (and derived languages) syntax


In C and derived languages, all data types, including those defined by the user, can be declared const, and
const-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 increases
the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it
communicates information about a value's intended use. This can help the compiler as well as the developer when
reasoning about code. It can also enable an optimizing compiler to generate more efficient code.

Simple data types


For simple non-pointer data types, applying the const qualifier is straightforward. It can go on either side of the
type 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) generates
a warning but not an error.

Pointers and references


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

* ptr,
const * ptrToConst,
* const constPtr,
const * const constPtrToConst )

Const-correctness
{
*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 the
pointer, indicating dereferencing. For example, in the declaration int *ptr, the dereferenced form *ptr is an
int, 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 the
type to the left. int const * ptrToConst can thus be read as "*ptrToConst is a int const" (the
value 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 right
to left. Thus, everything to the left of the star can be identified as the pointee type and everything to the right of the
star are the pointer properties. For instance, in our example above, int const * can be read as a writable pointer
that refers to a non-writable integer, and int * const can be read as a non-writable pointer that refers to a
writable 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 preceding
type, 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;

35

Const-correctness
Note, however, that despite the different convention for formatting C++ code, the semantics of pointer declaration
are 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 this
issue.[2]
C++ references follow similar rules. A declaration of a const reference is redundant since references can never be
made 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) to
pointers; however, someWikipedia:Manual of Style/Words to watch#Unsupported attributions have argued that these
are confusing and error-prone and that they therefore should generally be avoided or replaced with higher-level
structures.

Parameters and variables


const 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 a
constant, 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 int
x_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 does
not modify the parameter (it is a single assignment). For this reason, some favor using const in parameters only
for pass-by-reference, where it changes the contract, but not for pass-by-value, where it exposes the implementation.

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

36

Const-correctness
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" pointer
to 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 quite
different 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 thus
whether or not the caller is given a reference with which he can manipulate or only observe the private data in the
object. 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 returning
the int by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as
in the Standard Template Library.)

37

Const-correctness

Loopholes to const-correctness
There are several loopholes to pure const-correctness in C and C++. They exist primarily for compatibility with
existing code.
The first, which applies only to C++, is the use of const_cast, which allows the programmer to strip the const
qualifier, making any object modifiable. The necessity of stripping the qualifier arises when using existing code and
libraries 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 in
undefined behavior according to the ISO C++ Standard. In the example above, if ptr references a global, local, or
member variable declared as const, or an object allocated on the heap via new const int, the code is only
correct 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 are
allowed to be defined with an initial value. However, the initializer can use only constants like string constants and
other literals, and are not allowed to use non-constant elements like variable names, whether the initializer elements
are declared const or not, or whether the static duration variable is being declared const or not. There is a
non-portable way to initialize a const variable that has static storage duration. By carefully constructing a typecast
on the left hand side of a later assignment, a const variable can be written to, effectively stripping away the
const attribute and 'initializing' it with non-constant elements like other const variables and such. Writing into a
const variable this way may work as intended, but it causes undefined behavior and seriously contradicts
const-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

38

Const-correctness

39

containing object that is const has all const members except that member pointees (and referees) are still
mutable. To illustrate, consider this code:
struct S
{
int val;
int *ptr;
};
void Foo(const S
{
int i = 42;
s.val = i;
s.ptr = &i;
*s.ptr = i;

& s)

// Error: s is const, so val is a const int


// Error: s is const, so ptr is a const pointer to int
// 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 pointee
accessible through s.ptr is still modifiable, though this may not be desirable from the standpoint of
const-correctness because s might solely own the pointee. For this reason, someWikipedia:Manual of
Style/Words to watch#Unsupported attributions have argued that the default for member pointers and references
should be "deep" const-ness, which could be overridden by a mutable qualifier when the pointee is not owned
by the container, but this strategy would create compatibility issues with existing code. Thus, for historical
reasonsWikipedia: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 such
classes either don't support the usual copy semantics from a const object (implying that the containing class
cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of const-ness
through inadvertent or intentional copying.
Finally, several functions in the C standard library violate const-correctness, as they accept a const pointer to a
character string and return a non-const pointer to a part of the same string. strtol and strchr are among
these functions. Some implementations of the C++ standard library, such as Microsoft's try to close this loophole by
providing two overloaded versions of some functions: a "const" version and a "non-const" version.

Volatile-correctness
The other qualifier in C and C++, volatile, indicates that an object may be changed by something external to the
program 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 and
device drivers) and in multithreaded applications (though often used incorrectly in that context; see external links at
volatile 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 similar
design-by-contract strategy which Andrei Alexandrescu calls volatile-correctness,[3] though this is far less
common than const-correctness. The volatile qualifier also can be stripped by const_cast, and it can be
combined 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);

Const-correctness

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 two
successive reads even though the programmer cannot modify it. The semantics here indicate that the register's value
is read-only but not necessarily unchanging.

const and immutable in D


In Version 2 of the D programming language, two keywords relating to const exist. The immutable keyword
denotes data that cannot be modified through any reference. The const keyword denotes a non-mutable view of
mutable data. Unlike C++ const, D const and immutable are "deep" or transitive, and anything reachable
through 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).

40

Const-correctness

final in Java
In 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 be
performed only once, or the class will not compile. Java's final and C++'s const keywords have the same
meaning 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++, one
can 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 is
modifiable. I.e. *bar = value is valid. It just can't point to another location. Final reference in Java work the
same 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 accessing
objects in Java, and Java does not use stars to indicate them. For example i in the last example is a pointer and can
be 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 bar
pointer. There is no equivalent mechanism in Java. Thus there are also no const methods. Const-correctness
cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing
this around, one can ensure that objects can be passed around the system in a way that they cannot be modified. Java
collections framework provides a way to create unmodifiable wrapper of a Collection via
Collections.unmodifiableCollection() and similar methods.
Methods in Java can be declared "final", but that has a completely unrelated meaning - it means that the method
cannot be overridden in subclasses.
Interestingly, the Java language specification regards const as a reserved keyword i.e., one that cannot be used
as variable identifier but assigns no semantics to it. It is thought that the reservation of the keyword occurred to
allow for an extension of the Java language to include C++-style const methods and pointer to const
type.Wikipedia:Citation needed An enhancement request ticket for implementing const correctness exists in the
Java Community Process, but was closed in 2005 on the basis that it was impossible to implement in a
backwards-compatible fashion.

41

Const-correctness

const and readonly in C#


In C#, the qualifier readonly has the same effect on data members that final does in Java and the const
does in C++; the const modifier in C# has an effect similar (yet typed and class-scoped) to that of #define in
C++. (The other, inheritance-inhibiting effect of Java's final when applied to methods and classes is induced in
C# 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 pass
around read-only subclasses, and the .NET Framework provides some support for converting mutable collections to
immutable 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++ Experts
Forum

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

42

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 can
be overridden within an inheriting class by a function with the same signature. This concept is an important part of
the polymorphism portion of object-oriented programming (OOP).

Purpose
Further information: Dynamic dispatch
The 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 may
be referred to via a pointer or reference of the base class type instead of the derived class type. If there are base class
methods overridden by the derived class, the method actually called by such a reference or pointer can be bound
either 'early' (by the compiler), according to the declared type of the pointer or reference, or 'late' (i.e. by the runtime
system 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's
implementation of the function is called according to the actual type of the object referred to, regardless of the
declared type of the pointer or reference. If it is not 'virtual', the method is resolved 'early' and the function called is
selected 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 is
compiled.
In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the base
class. This modifier is inherited by all implementations of that method in derived classes, meaning that they can
continue to over-ride each other and be late-bound.

Virtual function

44

Example
For example, a base class Animal
could have a virtual function eat.
Subclass Fish would implement
eat()
differently than subclass
Wolf, but one can invoke eat() on
any class instance referred to as
Animal, and get the eat() behavior
of the specific subclass.

Class Diagram of Animal

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 calling
eat()), without needing to know what kind of animal may be in the list, how each animal eats, or what the
complete set of possible animal types might be.

Abstract classes and pure virtual functions


A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a
derived class if that class is not abstract. Classes containing pure virtual methods are termed "abstract" and they
cannot be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited pure
virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a
declaration (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

Virtual function
abstract concept whose behaviour is defined solely for each given kind (subclass) of MathSymbol. Similarly, a
given 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 methods
in C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviour
that 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 - similar
to what the interface keyword in Java explicitly specifies. In such a use, derived classes will supply all
implementations. In such a design pattern, the abstract class which serves as an interface will contain only pure
virtual functions, but no data members or ordinary methods. In C++, using such purely abstract classes as interfaces
works because C++ supports multiple inheritance. However, because many OOP languages do not support multiple
inheritance, they often provide a separate interface mechanism. An example is the Java programming language.

Behavior during construction and destruction


Languages 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 an
object. While it is recommended that virtual function calls in constructors should be avoided for C++, in some other
languages, for example C# and Java, the derived implementation can be called during construction and design
patterns such as the Abstract Factory Pattern actively promote this usage in languages supporting the ability.

Virtual destructors
Object-oriented languages typically manage memory allocation and de-allocation automatically when objects are
created and destroyed. However, some object-oriented languages allow a custom destructor method to be
implemented, 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 in
question. 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 static
dispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer type
that is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless the
destructor is virtual. This is particularly the case with C++, where the behavior is a common source of programming
errors.

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

45

Template (C++)

Template (C++)
Templates are a feature of the C++ programming language that allow functions and classes to operate with generic
types. 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 and
operator overloading. The C++ Standard Library provides many useful functions within a framework of connected
templates.
Major inspirations for C++ templates were the parametrized modules provided by CLU and the generics provided by
Ada.

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

Function templates
A function template behaves like a function except that the template can have arguments of many different types (see
example). In other words, a function template represents a family of functions. The format for declaring function
templates 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 introduced
to avoid confusion because a type parameter does not need to be a class, it may also be a basic type like int or
doubleWikipedia: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 the
source code file (in addition to limiting changes to one function description) versus separate functions written for
various datatypes, it does not produce smaller object code than would occur from separate non-templated versions of
a 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 object
code version that takes doubles. The compiler output will be identical to what would have been produced if the
source code contained two non-templated versions of max(), one written to handle ints and one written to handle
doubles.
#include <iostream>
int main(int, char**)
{

46

Template (C++)
// This will
std::cout <<
// This will
std::cout <<
// This type
std::cout <<
return 0;

47
call max <int> (by argument deduction)
max(3, 7) << std::endl;
call max<double> (by argument deduction)
max(3.0, 7.0) << std::endl;
is ambiguous, so explicitly instantiate max<double>
max<double>(3, 7.0) << std::endl;

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

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

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

Explicit template specialization


Sometimes, the programmer may decide to implement a special version of a function (or class) for a given set of
template type arguments which is called an explicit specialization. In this way certain template types can have a
specialized implementation that is optimized for the type or more meaningful implementation than the generic
implementation.
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 template
parameters must deviate from the generic behavior: that is, from the code generated by the main template, or
templates. 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;
}

Template (C++)

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

Advantages and disadvantages


Some uses of templates, such as the maximum() function, were previously fulfilled by function-like preprocessor
macros. 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 are
only expanded inline when the compiler deems it appropriate. When expanded inline, macro functions and function
templates have no extraneous runtime overhead. Template functions with many lines of code will incur runtime
overhead when they are not expanded inline, but the reduction in code size may help the code to load from disk more
quickly or fit within RAM caches.
Templates are considered type-safe; that is, they require type-checking at compile time. Hence, the compiler can
determine at compile time whether the type associated with a template definition can perform all of the functions
required 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. 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 to
code bloat, resulting in larger executables.
4. Because a template by its nature exposes its implementation, injudicious use in large systems can lead to longer
build times.
5. It can be difficult to debug code that is developed using templates. Since the compiler replaces the templates, it
becomes difficult for the debugger to locate the code at runtime.
6. Templates of Templates (nesting) are not supported by all compilers, or might have a max nesting level.
7. Templates are in the headers, which require a complete rebuild of all project pieces when changes are made.
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 text
editors) which analyze source code syntactically. It is difficult for such tools to determine whether a use of these
tokens 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 a
declaration of a constructor for class foo taking a parameter d whose type is the parameterized a < b, c >.

48

Template (C++)

Generic programming features in other languages


Initially, the concept of templates was not included in some languages, such as Java and C# 1.0. Java's adoption of
generics 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 the
basic behavior of C++ templates.[1] Some of the advanced template features utilized by libraries such as Boost and
STLSoft, 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 with
generics.
The D programming language attempts to build on C++ redesigning a better template system.[2] A significant
addition is the inclusion of the static if statement, which allows conditional compilation of code based on any
information 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 of
templates.
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 .. $])

49

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 arguments
expanded at compile time.
D templates allow a simple form of Constraints too. They can be expressed as an arbitrarily complex predicate that
must evaluate at compile time. If it's true the template is a match for the arguments, otherwise the template is ignored
during overload matching.[3]
template Foo(int N) if (N & 1)
{...} // A
template Foo(int N) if (!(N & 1)) {...} // B
Foo!(3)
Foo!(64)

// Instantiates A
// 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 the
Factorial 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.

Template (C++)

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)

51

Article Sources and Contributors

Article Sources and Contributors


C++ 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 Monroe
III, 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, Andre
Engels, 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, Dawn
Bard, 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, Elven
Spellmaker, 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, Franois Robere, Freakofnurture, Frecklefoot, Free
Software 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, King
of 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 Jaczuk, 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 Abrock, 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, Mikrosam
Akademija 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, Mystc, 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, Oleg
Alexandrov, 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, Rich
Farmbrough, 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, Sasha
Slutsker, 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 namespace
initialisation 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, Whalelover
Frost, 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 Arnfjr 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. Jnos, Urod, Wikiwonky, Wing gundam, Yshalabi, Zundark, Zvika, var Arnfjr
Bjarmason, 76 anonymous edits

52

Article Sources and Contributors


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, Lone
boatman, 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, Ouz 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, Tony
Sidaway, 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, Swog, 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, Maximus
Rex, 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, Sir
Anguilla, Smyth, Spiel496, Spoon!, Steveha, TakuyaMurata, TheIncredibleEdibleOompaLoompa, Timphilipw, TomJF, Torc2, Tsunanet, Wbm1058, Wdyoung, Wlievens, XP1, 94 anonymous
edits
Virtual function Source: http://en.wikipedia.org/w/index.php?oldid=617213124 Contributors: .digamma, A Quest For Knowledge, AKEB, Abdull, Achowat, Akihabara, AlexPlank, Andreas
Kaufmann, 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

53

Image Sources, Licenses and Contributors

Image Sources, Licenses and Contributors


file: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 Juhasz
Image:ClassDiagram for VirtualFunction.png Source: http://en.wikipedia.org/w/index.php?title=File:ClassDiagram_for_VirtualFunction.png License: Public Domain Contributors:
OnionBulb

54

License

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

55

You might also like