Part I. The Boost C++ Libraries
Libraries Listed Alphabetically
Libraries Listed by Category
String and text processing
Containers
Iterators
Algorithms
Function objects and higher-order programming
Generic programming
Template metaprogramming
Preprocessor metaprogramming
Concurrent programming
Math and numerics
Correctness and testing
Data structures
Input/Output
Inter-language support
Memory
Parsing
Miscellaneous
Broken compiler workarounds
Boost.Any
Introduction
Examples
Reference
ValueType requirements
Header <boost/any.hpp>
Class bad_any_cast
Class any
Function any_cast
Acknowledgements
Boost.Array
Introduction
Reference
Header <boost/array.hpp>
Class template array
Design Rationale
For more information...
Acknowledgements
Concept reference
Concepts
Concept Assignable
Concept InputIterator
Concept OutputIterator
Concept ForwardIterator
Concept BidirectionalIterator
Concept RandomAccessIterator
Concept DefaultConstructible
Concept CopyConstructible
Concept EqualityComparable
Concept LessThanComparable
Concept SignedInteger
Boost.Date_Time
Conceptual
Motivation
Domain Concepts
Design Concepts
More Information
Gregorian
Date Class
Date Duration (aka Days)
Date Period
Date Iterators
Date Generators/Algorithms
Gregorian Calendar
Class day_clock
Posix Time
Ptime Class
Time Duration
Time Period
Time Iterators
Local Time Adjustment
Details
Calculations
Design Goals
Tradeoffs: Stability, Predictability, and Approximations
Serialization
Terminology
References
Build-Compiler Information
Tests
Change History
Acknowledgements
Examples
General Usage Examples
Dates as Strings
Days Alive
Days Between New Years
End of the Months
Localization Demonstration
Date Period Calculations
Print Holidays
Print Month
Month Adding
Time Math
Print Hours
Local to UTC Conversion
Time Periods
Library Reference
Date Time Reference
Header <boost/date_time/adjust_functors.hpp>
Class template day_functor
Class template month_functor
Class template week_functor
Class template year_functor
Header <boost/date_time/c_local_time_adjustor.hpp>
Class template c_local_adjustor
Header <boost/date_time/c_time.hpp>
Header <boost/date_time/compiler_config.hpp>
Header <boost/date_time/constrained_value.hpp>
Class template constrained_value
Class template simple_exception_policy
Header <boost/date_time/date.hpp>
Class template date
Header <boost/date_time/date_clock_device.hpp>
Class template day_clock
Header <boost/date_time/date_defs.hpp>
Header <boost/date_time/date_duration.hpp>
Class template date_duration
Struct duration_traits_long
Struct duration_traits_adapted
Header <boost/date_time/date_duration_types.hpp>
Class template weeks_duration
Class template months_duration
Class template years_duration
Header <boost/date_time/date_format_simple.hpp>
Class template simple_format
Class simple_format<wchar_t>
Header <boost/date_time/date_formatting.hpp>
Class template month_formatter
Class template ymd_formatter
Class template date_formatter
Header <boost/date_time/date_formatting_limited.hpp>
Header <boost/date_time/date_formatting_locales.hpp>
Class template ostream_month_formatter
Class template ostream_weekday_formatter
Class template ostream_ymd_formatter
Class template ostream_date_formatter
Header <boost/date_time/date_generators.hpp>
Class template year_based_generator
Class template partial_date
Class template nth_kday_of_month
Class template first_kday_of_month
Class template last_kday_of_month
Class template first_kday_after
Class template first_kday_before
Function template days_until_weekday
Function template days_before_weekday
Function template next_weekday
Function template previous_weekday
Header <boost/date_time/date_iterator.hpp>
Class template date_itr_base
Class template date_itr
Header <boost/date_time/date_names_put.hpp>
Class template date_names_put
Class template all_date_names_put
Header <boost/date_time/dst_rules.hpp>
Class template dst_calculator
Class template dst_calc_engine
Class template us_dst_rules
Class template null_dst_rules
Header <boost/date_time/dst_transition_generators.hpp>
Class template dst_day_calc_rule
Class template day_calc_dst_rule
Header <boost/date_time/filetime_functions.hpp>
Function template time_from_ftime
Header <boost/date_time/gregorian_calendar.hpp>
Class template gregorian_calendar_base
Header <boost/date_time/int_adapter.hpp>
Class template int_adapter
Function template operator<<
Header <boost/date_time/iso_format.hpp>
Class template iso_format_base
Class iso_format_base<wchar_t>
Class template iso_format
Class template iso_extended_format
Header <boost/date_time/local_time_adjustor.hpp>
Class template utc_adjustment
Class template dynamic_local_time_adjustor
Class template static_local_time_adjustor
Class template local_adjustor
Header <boost/date_time/local_timezone_defs.hpp>
Struct template us_dst_trait
Struct template eu_dst_trait
Struct template uk_dst_trait
Struct template acst_dst_trait
Header <boost/date_time/microsec_time_clock.hpp>
Class template microsec_clock
Header <boost/date_time/parse_format_base.hpp>
Type ymd_order_spec
Header <boost/date_time/period.hpp>
Class template period
Header <boost/date_time/special_defs.hpp>
Header <boost/date_time/time.hpp>
Class template base_time
Header <boost/date_time/time_clock.hpp>
Class template second_clock
Header <boost/date_time/time_defs.hpp>
Header <boost/date_time/time_duration.hpp>
Class template time_duration
Class template subsecond_duration
Header <boost/date_time/time_formatting_streams.hpp>
Class template ostream_time_duration_formatter
Class template ostream_time_formatter
Class template ostream_time_period_formatter
Header <boost/date_time/time_iterator.hpp>
Class template time_itr
Header <boost/date_time/time_parsing.hpp>
Function template parse_delimited_time_duration
Header <boost/date_time/time_resolution_traits.hpp>
Struct time_resolution_traits_bi32_impl
Struct time_resolution_traits_adapted32_impl
Struct time_resolution_traits_bi64_impl
Struct time_resolution_traits_adapted64_impl
Class template time_resolution_traits
Header <boost/date_time/time_system_counted.hpp>
Struct template counted_time_rep
Class template counted_time_system
Header <boost/date_time/time_system_split.hpp>
Class template split_timedate_system
Header <boost/date_time/wrapping_int.hpp>
Class template wrapping_int
Class template wrapping_int2
Header <boost/date_time/year_month_day.hpp>
Struct template year_month_day_base
Gregorian Reference
Header <boost/date_time/gregorian/formatters.hpp>
Header <boost/date_time/gregorian/formatters_limited.hpp>
Header <boost/date_time/gregorian/greg_calendar.hpp>
Class gregorian_calendar
Header <boost/date_time/gregorian/greg_date.hpp>
Class date
Header <boost/date_time/gregorian/greg_day.hpp>
Struct bad_day_of_month
Class greg_day
Header <boost/date_time/gregorian/greg_day_of_year.hpp>
Struct bad_day_of_year
Header <boost/date_time/gregorian/greg_duration.hpp>
Header <boost/date_time/gregorian/greg_duration_types.hpp>
Struct greg_durations_config
Header <boost/date_time/gregorian/greg_facet.hpp>
Struct greg_facet_config
Function template operator<<
Function template operator<<
Function template operator<<
Function template operator<<
Header <boost/date_time/gregorian/greg_month.hpp>
Struct bad_month
Class greg_month
Header <boost/date_time/gregorian/greg_weekday.hpp>
Struct bad_weekday
Class greg_weekday
Header <boost/date_time/gregorian/greg_year.hpp>
Struct bad_year
Class greg_year
Header <boost/date_time/gregorian/greg_ymd.hpp>
Header <boost/date_time/gregorian/gregorian.hpp>
Header <boost/date_time/gregorian/gregorian_types.hpp>
Header <boost/date_time/gregorian/parsers.hpp>
Posix Time Reference
Header <boost/date_time/posix_time/conversion.hpp>
Function template from_ftime
Header <boost/date_time/posix_time/date_duration_operators.hpp>
Function operator+
Function operator+=
Function operator-
Function operator-=
Function operator+
Function operator+=
Function operator-
Function operator-=
Header <boost/date_time/posix_time/posix_time.hpp>
Header <boost/date_time/posix_time/posix_time_config.hpp>
Class time_duration
Struct simple_time_rep
Class posix_time_system_config
Class millisec_posix_time_system_config
Header <boost/date_time/posix_time/posix_time_duration.hpp>
Class hours
Class minutes
Class seconds
Header <boost/date_time/posix_time/posix_time_system.hpp>
Header <boost/date_time/posix_time/posix_time_types.hpp>
Header <boost/date_time/posix_time/ptime.hpp>
Class ptime
Header <boost/date_time/posix_time/time_formatters.hpp>
Function template operator>>
Header <boost/date_time/posix_time/time_formatters_limited.hpp>
Header <boost/date_time/posix_time/time_parsers.hpp>
Function duration_from_string
Header <boost/date_time/posix_time/time_period.hpp>
Boost.Function
Introduction
History & Compatibility Notes
Tutorial
Basic Usage
Free functions
Member functions
References to Function Objects
Comparing Boost.Function function objects
Reference
Definitions
Header <boost/function.hpp>
Class bad_function_call
Class function_base
Class template functionN
Class template function
Header <boost/function_equal.hpp>
Function template function_equal
Frequently Asked Questions
Miscellaneous Notes
Boost.Function vs. Function Pointers
Performance
Function object wrapper size
Copying efficiency
Invocation efficiency
Combatting virtual function "bloat"
Acknowledgements
Testsuite
Acceptance tests
Negative tests
Boost.Lambda
In a nutshell
Getting Started
Installing the library
Conventions used in this document
Introduction
Motivation
Introduction to lambda expressions
Partial function application
Terminology
Using the library
Introductory Examples
Parameter and return types of lambda functors
About actual arguments to lambda functors
Storing bound arguments in lambda functions
Lambda expressions in details
Placeholders
Operator expressions
Operators that cannot be overloaded
Assignment and subscript operators
Logical operators
Comma operator
Function call operator
Member pointer operator
Bind expressions
Function pointers or references as targets
Member functions as targets
Member variables as targets
Function objects as targets
Overriding the deduced return type
Nullary lambda functors and ret
Delaying constants and variables
Lambda expressions for control structures
Switch statement
Exceptions
Construction and destruction
Special lambda expressions
Preventing argument substitution
Unlambda
Protect
Rvalues as actual arguments to lambda functors
Casts, sizeof and typeid
Cast expressions
Sizeof and typeid
Nesting STL algorithm invocations
Extending return type deduction system
Practical considerations
Performance
About compiling
Portability
Test coverage
Relation to other Boost libraries
Boost Function
Boost Bind
First argument of bind expression
Contributors
Appendix A. Rationale for some of the design decisions
Lambda functor arity
Bibliography
Boost.Program_options
Introduction
Tutorial
Getting Started
Option Details
Multiple Sources
Library Overview
Options Description Component
Syntactic information
Semantic information
Positional options
Parsers Component
Storage Component
Annotated List of Symbols
How To
Non-conventional Syntax
Response Files
Winmain Command Line
Option Groups and Hidden Options
Custom Validators
Unicode Support
Design Discussion
Unicode Support
Acknowledgements
Reference
Header <boost/program_options/cmdline.hpp>
Type style_t
Header <boost/program_options/environment_iterator.hpp>
Class environment_iterator
Header <boost/program_options/eof_iterator.hpp>
Class template eof_iterator
Header <boost/program_options/errors.hpp>
Class error
Class invalid_syntax
Class unknown_option
Class ambiguous_option
Class multiple_values
Class multiple_occurrences
Class validation_error
Class invalid_option_value
Class too_many_positional_options_error
Class too_few_positional_options_error
Class invalid_command_line_syntax
Class invalid_command_line_style
Header <boost/program_options/option.hpp>
Class template basic_option
Header <boost/program_options/options_description.hpp>
Class option_description
Class options_description_easy_init
Class options_description
Class duplicate_option_error
Header <boost/program_options/parsers.hpp>
Class template basic_parsed_options
Class basic_parsed_options<wchar_t>
Class common_command_line_parser
Class template basic_command_line_parser
Function template parse_command_line
Function template parse_config_file
Function parse_environment
Function parse_environment
Header <boost/program_options/positional_options.hpp>
Class positional_options_description
Header <boost/program_options/value_semantic.hpp>
Class value_semantic
Class template value_semantic_codecvt_helper
Class value_semantic_codecvt_helper<char>
Class value_semantic_codecvt_helper<wchar_t>
Class untyped_value
Class template typed_value
Function value
Function wvalue
Function bool_switch
Header <boost/program_options/variables_map.hpp>
Class variable_value
Class abstract_variables_map
Class variables_map
Function store
Function store
Function notify
Header <boost/program_options/version.hpp>
Macro BOOST_PROGRAM_OPTIONS_VERSION
Boost.Ref
Introduction
Reference
Header <boost/ref.hpp>
Class template reference_wrapper
Class template is_reference_wrapper
Class template unwrap_reference
Acknowledgements
Boost.Signals
Introduction
Tutorial
How to Read this Tutorial
Compatibility Note
Hello, World! (Beginner)
Calling multiple slots
Connecting multiple slots (Beginner)
Ordering slot call groups (Intermediate)
Passing values to and from slots
Slot Arguments (Beginner)
Signal Return Values (Advanced)
Connection Management
Disconnecting Slots (Beginner)
Scoped connections (Intermediate)
Disconnecting equivalent slots (Intermediate)
Automatic connection management (Intermediate)
When can disconnections occur? (Intermediate)
Passing slots (Intermediate)
Linking against the Signals library
Reference
Header <boost/signal.hpp>
Class template signalN
Class template signal
Header <boost/signals/slot.hpp>
Class template slot
Header <boost/signals/trackable.hpp>
Class trackable
Header <boost/signals/connection.hpp>
Class connection
Class scoped_connection
Header <boost/visit_each.hpp>
Function template visit_each
Header <boost/last_value.hpp>
Class template last_value
Class last_value<void>
Frequently Asked Questions
Design Overview
Type Erasure
connection class
Slot Call Iterator
visit_each function template
Design Rationale
Choice of Slot Definitions
User-level Connection Management
Combiner Interface
Connection Interfaces: += operator
trackable rationale
trackable copying behavior
Why derivation from trackable?
Comparison with other Signal/Slot implementations
libsigc++
.NET delegates
Testsuite
Acceptance tests
Boost String Algorithms Library
Introduction
Usage
First Example
Case conversion
Predicates and Classification
Trimming
Find algorithms
Replace Algorithms
Find Iterator
Split
Quick Reference
Algorithms
Finders and Formatters
Iterators
Classification
Design Topics
String Representation
iterator_range class
Collection Traits
Sequence Traits
Find Algorithms
Replace Algorithms
Find Iterators & Split Algorithms
Exception Safety
Concepts
Definitions
Finder Concept
Formatter concept
Reference
Header <boost/algorithm/string/case_conv.hpp>
Function to_lower_copy
Function template to_lower
Function to_upper_copy
Function template to_upper
Header <boost/algorithm/string/classification.hpp>
Function is_classified
Function is_space
Function is_alnum
Function is_alpha
Function is_cntrl
Function is_digit
Function is_graph
Function is_lower
Function is_print
Function is_punct
Function is_upper
Function is_xdigit
Function template is_any_of
Function template is_from_range
Function template operator&&
Function template operator||
Function template operator!
Header <boost/algorithm/string/collection_traits.hpp>
Struct template collection_traits
Struct template value_type_of
Struct template difference_type_of
Struct template iterator_of
Struct template const_iterator_of
Struct template result_iterator_of
Function template size
Function template empty
Function begin
Function end
Header <boost/algorithm/string/compare.hpp>
Struct is_equal
Struct is_iequal
Header <boost/algorithm/string/concept.hpp>
Struct template FinderConcept
Struct template FormatterConcept
Header <boost/algorithm/string/constants.hpp>
Type token_compress_mode_type
Header <boost/algorithm/string/erase.hpp>
Function erase_range_copy
Function template erase_range
Function erase_first_copy
Function template erase_first
Function ierase_first_copy
Function template ierase_first
Function erase_last_copy
Function template erase_last
Function ierase_last_copy
Function template ierase_last
Function erase_nth_copy
Function template erase_nth
Function ierase_nth_copy
Function template ierase_nth
Function erase_all_copy
Function template erase_all
Function ierase_all_copy
Function template ierase_all
Function erase_head_copy
Function template erase_head
Function erase_tail_copy
Function template erase_tail
Header <boost/algorithm/string/find.hpp>
Function template find
Function template find_first
Function template ifind_first
Function template find_last
Function template ifind_last
Function template find_nth
Function template ifind_nth
Function template find_head
Function template find_tail
Function template find_token
Header <boost/algorithm/string/find_format.hpp>
Function find_format_copy
Function template find_format
Function find_format_all_copy
Function template find_format_all
Function template regex_finder
Function template regex_formatter
Header <boost/algorithm/string/find_iterator.hpp>
Class template find_iterator
Class template split_iterator
Function template make_find_iterator
Function template make_split_iterator
Header <boost/algorithm/string/finder.hpp>
Function first_finder
Function last_finder
Function nth_finder
Function head_finder
Function tail_finder
Function template token_finder
Function range_finder
Header <boost/algorithm/string/formatter.hpp>
Function template const_formatter
Function template identity_formatter
Function template empty_formatter
Header <boost/algorithm/string/iterator_range.hpp>
Class template iterator_range
Function template operator<<
Function template make_iterator_range
Function template make_iterator_range
Function template copy_iterator_range
Function template transform_iterator_range
Header <boost/algorithm/string/predicate.hpp>
Function starts_with
Function template istarts_with
Function ends_with
Function template iends_with
Function contains
Function template icontains
Function equals
Function template iequals
Function template all
Header <boost/algorithm/string/regex.hpp>
Function template find_regex
Function replace_regex_copy
Function template replace_regex
Function replace_all_regex_copy
Function template replace_all_regex
Function erase_regex_copy
Function template erase_regex
Function erase_all_regex_copy
Function template erase_all_regex
Function template find_all_regex
Function template split_regex
Header <boost/algorithm/string/regex_find_format.hpp>
Function template regex_finder
Function template regex_formatter
Header <boost/algorithm/string/replace.hpp>
Function replace_range_copy
Function template replace_range
Function replace_first_copy
Function template replace_first
Function ireplace_first_copy
Function template ireplace_first
Function replace_last_copy
Function template replace_last
Function ireplace_last_copy
Function template ireplace_last
Function replace_nth_copy
Function template replace_nth
Function ireplace_nth_copy
Function template ireplace_nth
Function replace_all_copy
Function template replace_all
Function ireplace_all_copy
Function template ireplace_all
Function replace_head_copy
Function template replace_head
Function replace_tail_copy
Function template replace_tail
Header <boost/algorithm/string/sequence_traits.hpp>
Class template has_native_replace
Class template has_stable_iterators
Class template has_const_time_insert
Class template has_const_time_erase
Header <boost/algorithm/string/split.hpp>
Function template find_all
Function template ifind_all
Function template split
Header <boost/algorithm/string/std_containers_traits.hpp>
Header <boost/algorithm/string.hpp>
Header <boost/algorithm/string_regex.hpp>
Header <boost/algorithm/string/trim.hpp>
Function trim_left_copy_if
Function template trim_left_copy
Function template trim_left_if
Function template trim_left
Function trim_right_copy_if
Function template trim_right_copy
Function template trim_right_if
Function template trim_right
Function trim_copy_if
Function template trim_copy
Function template trim_if
Function template trim
Rationale
Locales
Regular Expressions
Environment
Build
Examples
Tests
Portability
Credits
Acknowledgments
Boost.Threads
Overview
Introduction
Dangers
General considerations
Testing and debugging considerations
Getting a head start
C++ Standard Library usage in multithreaded programs
Runtime libraries
Potentially non-thread-safe functions
Common guarantees for all Boost.Threads components
Exceptions
NonCopyable requirement
Design
Goals
Iterative Phases
Phase 1, Synchronization Primitives
Phase 2, Thread Management and Thread Specific Storage
The Next Phase
Concepts
Mutexes
Locking Strategies
Recursive Locking Strategy
Checked Locking Strategy
Unchecked Locking Strategy
Unspecified Locking Strategy
Scheduling Policies
FIFO Scheduling Policy
Priority Driven Policy
Unspecified Policy
Mutex Concepts
Mutex Concept
TryMutex Concept
TimedMutex Concept
Mutex Models
Lock Concepts
Lock Concept
ScopedLock Concept
TryLock Concept
ScopedTryLock Concept
TimedLock Concept
ScopedTimedLock Concept
Lock Models
Read/Write Mutexes
Locking Strategies
Recursive Locking Strategy
Checked Locking Strategy
Unchecked Locking Strategy
Unspecified Locking Strategy
Thread Identification
Lock Promotion
Lock Demotion
Scheduling Policies
Inter-Class Scheduling Policies
ReaderPriority
WriterPriority
AlternatingPriority/ManyReads
AlternatingPriority/SingleRead
Intra-Class Scheduling Policies
Mutex Concepts
ReadWriteMutex Concept
TryReadWriteMutex Concept
TimedReadWriteMutex Concept
Mutex Models
Lock Concepts
ReadWriteLock Concept
ScopedReadWriteLock Concept
TryReadWriteLock Expressions
ScopedTryReadWriteLock Expressions
TimedReadWriteLock Concept
ScopedTimedReadWriteLock Concept
Lock Models
Rationale
Rationale for the Creation of Boost.Threads
Rationale for the Low Level Primitives Supported in Boost.Threads
Rationale for the Lock Design
Rationale for NonCopyable Thread Type
1. Use case: Simple creation of a thread.
2. Use case: Creation of a thread that's later joined.
3. Use case: Simple creation of several threads in a loop.
4. Use case: Creation of several threads in a loop which are later joined.
5. Use case: Creation of a thread whose ownership is passed to another object/method.
6. Use case: Creation of a thread whose ownership is shared between multiple objects.
1. Comparison: simple creation of a thread.
2. Comparison: creation of a thread that's later joined.
3. Comparison: simple creation of several threads in a loop.
4. Comparison: creation of several threads in a loop which are later joined.
5. Comparison: creation of a thread whose ownership is passed to another object/method.
6. Comparison: creation of a thread whose ownership is shared between multiple objects.
Rationale for not providing Event Variables
Reference
Header <boost/thread/barrier.hpp>
Class barrier
Header <boost/thread/condition.hpp>
Class condition
Header <boost/thread/exceptions.hpp>
Class lock_error
Class thread_resource_error
Header <boost/thread/mutex.hpp>
Class mutex
Class try_mutex
Class timed_mutex
Header <boost/thread/once.hpp>
Macro BOOST_ONCE_INIT
Function call_once
Header <boost/thread/recursive_mutex.hpp>
Class recursive_mutex
Class recursive_try_mutex
Class recursive_timed_mutex
Header <boost/thread/read_write_mutex.hpp>
Type read_write_scheduling_policy
Class read_write_mutex
Class try_read_write_mutex
Class timed_read_write_mutex
Header <boost/thread/thread.hpp>
Class thread
Class thread_group
Header <boost/thread/tss.hpp>
Class thread_specific_ptr
Header <boost/thread/xtime.hpp>
Type xtime_clock_types
Struct xtime
Frequently Asked Questions
Configuration
Library Defined Public Macros
Library Defined Implementation Macros
Build
Building the Boost.Threads Libraries
Testing the Boost.Threads Libraries
Implementation Notes
Win32
Release Notes
Boost 1.32.0
Documentation converted to BoostBook
Statically-link build option added
Barrier functionality added
Read/write mutex functionality added
Thread-specific pointer functionality changed
Mutex implementation changed for Win32
Windows CE support improved
Glossary
Acknowledgements
Acknowledgements
Bibliography
Boost.Tribool
Introduction
Tutorial
Basic usage
Renaming the indeterminate state
tribool input/output
Reference
Header <boost/logic/tribool.hpp>
Class tribool
Function indeterminate
Function operator!
Function operator&&
Function operator||
Function operator==
Function operator!=
Macro BOOST_TRIBOOL_THIRD_STATE
Header <boost/logic/tribool_fwd.hpp>
Header <boost/logic/tribool_io.hpp>
Class template indeterminate_name
Function template get_default_indeterminate_name
Function template operator<<
Function template operator>>
Testsuite
Acceptance tests
Boost.Variant
Introduction
Abstract
Motivation
Problem
Solution: A Motivating Example
Tutorial
Basic Usage
Advanced Topics
Preprocessor macros
Using a type sequence to specify bounded types
Recursive variant types
Recursive types with recursive_wrapper
Recursive types with make_recursive_variant
Binary visitation
Reference
Concepts
BoundedType
StaticVisitor
Examples
OutputStreamable
Header <boost/variant.hpp>
Header <boost/variant/variant_fwd.hpp>
Macro BOOST_VARIANT_LIMIT_TYPES
Macro BOOST_VARIANT_ENUM_PARAMS
Macro BOOST_VARIANT_ENUM_SHIFTED_PARAMS
Macro BOOST_VARIANT_NO_REFERENCE_SUPPORT
Macro BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
Macro BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
Header <boost/variant/variant.hpp>
Class template variant
Function template swap
Function template operator<<
Class template make_variant_over
Header <boost/variant/recursive_variant.hpp>
Class template make_recursive_variant
Class template make_recursive_variant_over
Header <boost/variant/recursive_wrapper.hpp>
Class template recursive_wrapper
Class template is_recursive_wrapper
Class template unwrap_recursive_wrapper
Header <boost/variant/apply_visitor.hpp>
Class template apply_visitor_delayed_t
Function apply_visitor
Header <boost/variant/get.hpp>
Class bad_get
Function get
Header <boost/variant/bad_visit.hpp>
Class bad_visit
Header <boost/variant/static_visitor.hpp>
Class template static_visitor
Header <boost/variant/visitor_ptr.hpp>
Class template visitor_ptr_t
Function template visitor_ptr
Design Overview
"Never-Empty" Guarantee
The Guarantee
The Implementation Problem
The "Ideal" Solution: False Hopes
An Initial Solution: Double Storage
Current Approach: Temporary Heap Backup
Enabling Optimizations
Future Direction: Policy-based Implementation
Miscellaneous Notes
Boost.Variant vs. Boost.Any
Portability
Troubleshooting
"Template instantiation depth exceeds maximum"
GNU GCC
"Internal heap limit reached"
Microsoft Visual C++
Acknowledgments
References
Part II. The BoostBook Documentation Format
Introduction
Getting Started
Configuring local DocBook XSL and DTD distributions
Configuring Apache FOP for PostScript/PDF Output
Configuring Doxygen for Documentation Extraction
Troubleshooting
Documenting libraries
Defining a BoostBook library
From HTML to BoostBook
Sectioning in BoostBook
Bringing Together a BoostBook Document
Linking in BoostBook
Reference
BoostBook element class-specialization
BoostBook element link-test
BoostBook element link-fail-test
BoostBook element typedef
BoostBook element static-constant
BoostBook element code
BoostBook element destructor
BoostBook element template-type-parameter
BoostBook element description
BoostBook element librarylist
BoostBook element library-reference
BoostBook element boostbook
BoostBook element union
BoostBook element inherit
BoostBook element template-varargs
BoostBook element source
BoostBook element function
BoostBook element postconditions
BoostBook element compile-test
BoostBook element method
BoostBook element snippet
BoostBook element constructor
BoostBook element namespace
BoostBook element if-fails
BoostBook element free-function-group
BoostBook element functionname
BoostBook element librarycategory
BoostBook element notes
BoostBook element data-member
BoostBook element specialization
BoostBook element union-specialization
BoostBook element throws
BoostBook element template-arg
BoostBook element method-group
BoostBook element requirement
BoostBook element precondition
BoostBook element paramtype
BoostBook element using-class
BoostBook element run-test
BoostBook element librarypurpose
BoostBook element copy-assignment
BoostBook element run-fail-test
BoostBook element template
BoostBook element compile-fail-test
BoostBook element returns
BoostBook element default
BoostBook element parameter
BoostBook element signature
BoostBook element overloaded-function
BoostBook element class
BoostBook element librarycategorydef
BoostBook element type
BoostBook element enumvalue
BoostBook element overloaded-method
BoostBook element programlisting
BoostBook element complexity
BoostBook element purpose
BoostBook element template-nontype-parameter
BoostBook element library
BoostBook element librarycategorylist
BoostBook element using-namespace
BoostBook element struct-specialization
BoostBook element struct
BoostBook element lib
BoostBook element enum
BoostBook element requires
BoostBook element effects
BoostBook element libraryname
BoostBook element libraryinfo
BoostBook element testsuite
BoostBook element header
BoostBook element rationale
Part III. Boost.Build v2 User Manual
How to use this document
Installation
Tutorial
Hello, world
Properties
Build Requests and Target Requirements
Project Attributes
Project Hierarchies
Libraries and Dependent Targets
Library dependencies
Static and shared libaries
Conditions and alternatives
Prebuilt targets
User documentation
Configuration
Writing Jamfiles
Overview
Main targets
Projects
Additional Jamfile rules
Project root
Build process
Build request
Building a main target
Building a project
Builtin target types
Programs
Libraries
Alias
Installing
Testing
Builtin features
Differences to Boost.Build V1
Configuration
Writing Jamfiles
Build process
Extender Manual
Introduction
Target types
Scanners
Tools and generators
Features
Main target rules
Toolset modules
Detailed reference
General information
Initialization
Command line
Command line arguments
Command line options
Writing Jamfiles
Generated headers
Build process
Alternative selection
Determining common properties
Features and properties
Property Validity
Feature Attributes
Feature Declaration
Build Variants
Property refinement
Conditional properties
Target identifiers and references
Generators
Selecting and ranking viable generators
Running generators
Selecting dependency graph
Property adjustment
Transformations cache
Frequently Asked Questions
I'm getting "Duplicate name of actual target" error. What does it mean?
Accessing environment variables
How to control properties order?
How to control the library order on Unix?
Can I get output of external program as a variable in a Jamfile?
How to get the project-root location?
How to change compilation flags for one file?
Why are the dll-path and hardcode-dll-paths properties useful?
Targets in site-config.jam
Appendix B. Boost.Build v2 architecture
Overview
The build layer
The tools layer
Targets
Dependency scanning
Support for different scanning algorithms
Ability to scan the same file several times
Proper detection of dependencies on generated files.
Proper detection of dependencies from generated files
File targets
Types
Target paths

The Boost C++ Libraries
The Boost C++ Libraries

The Boost C++ Libraries

The Boost C++ Libraries

Table of Contents
I. The Boost C++ Libraries
Boost.Any
Introduction
Examples
Reference
ValueType
requirements
Header <boost/any.hpp>
Acknowledgements
Boost.Array
Introduction
Reference
Header <boost/array.hpp>
Design Rationale
For more information...
Acknowledgements
Boost.Date_Time
Conceptual
Motivation
Domain Concepts
Design Concepts
More Information
Gregorian
Date Class
Date Duration (aka Days)
Date Period
Date Iterators
Date Generators/Algorithms
Gregorian Calendar
Class day_clock
Posix Time
Ptime Class
Time Duration
Time Period
Time Iterators
Local Time Adjustment
Details
Calculations
Design Goals
Tradeoffs: Stability, Predictability, and Approximations
Serialization
Terminology
References
Build-Compiler Information
Tests
Change History
Acknowledgements
Examples
General Usage Examples
Dates as Strings
Days Alive
Days Between New Years
End of the Months
Localization Demonstration
Date Period Calculations
Print Holidays
Print Month
Month Adding
Time Math
Print Hours
Local to UTC Conversion
Time Periods
Library Reference
Date Time Reference
Gregorian Reference
Posix Time Reference
Boost.Function
Introduction
History & Compatibility Notes
Tutorial
Basic Usage
Free functions
Member functions
References to Function Objects
Comparing Boost.Function function objects
Reference
Definitions
Header <boost/function.hpp>
Header <boost/function_equal.hpp>
Frequently Asked Questions
Miscellaneous Notes
Boost.Function vs. Function Pointers
Performance
Combatting virtual function "bloat"
Acknowledgements
Testsuite
Acceptance tests
Negative tests
Boost.Lambda
In a nutshell
Getting Started
Installing the library
Conventions used in this document
Introduction
Motivation
Introduction to lambda expressions
Using the library
Introductory Examples
Parameter and return types of lambda functors
About actual arguments to lambda functors
Storing bound arguments in lambda functions
Lambda expressions in details
Placeholders
Operator expressions
Bind expressions
Overriding the deduced return type
Delaying constants and variables
Lambda expressions for control structures
Exceptions
Construction and destruction
Special lambda expressions
Casts, sizeof and typeid
Nesting STL algorithm invocations
Extending return type deduction system
Practical considerations
Performance
About compiling
Portability
Relation to other Boost libraries
Boost Function
Boost Bind
Contributors
Boost.Program_options
Introduction
Tutorial
Getting Started
Option Details
Multiple Sources
Library Overview
Options Description Component
Parsers Component
Storage Component
Annotated List of Symbols
How To
Non-conventional Syntax
Response Files
Winmain Command Line
Option Groups and Hidden Options
Custom Validators
Unicode Support
Design Discussion
Unicode Support
Acknowledgements
Reference
Header <boost/program_options/cmdline.hpp>
Header <boost/program_options/environment_iterator.hpp>
Header <boost/program_options/eof_iterator.hpp>
Header <boost/program_options/errors.hpp>
Header <boost/program_options/option.hpp>
Header <boost/program_options/options_description.hpp>
Header <boost/program_options/parsers.hpp>
Header <boost/program_options/positional_options.hpp>
Header <boost/program_options/value_semantic.hpp>
Header <boost/program_options/variables_map.hpp>
Header <boost/program_options/version.hpp>
Boost.Ref
Introduction
Reference
Header <boost/ref.hpp>
Acknowledgements
Boost.Signals
Introduction
Tutorial
How to Read this Tutorial
Compatibility Note
Hello, World! (Beginner)
Calling multiple slots
Passing values to and from slots
Connection Management
Linking against the Signals library
Reference
Header <boost/signal.hpp>
Header <boost/signals/slot.hpp>
Header <boost/signals/trackable.hpp>
Header <boost/signals/connection.hpp>
Header <boost/visit_each.hpp>
Header <boost/last_value.hpp>
Frequently Asked Questions
Design Overview
Type Erasure
connection
class
Slot Call Iterator
visit_each
function template
Design Rationale
Choice of Slot Definitions
User-level Connection Management
Combiner Interface
Connection Interfaces: += operator
trackable
rationale
Comparison with other Signal/Slot implementations
Testsuite
Acceptance tests
Boost String Algorithms Library
Introduction
Usage
First Example
Case conversion
Predicates and Classification
Trimming
Find algorithms
Replace Algorithms
Find Iterator
Split
Quick Reference
Algorithms
Finders and Formatters
Iterators
Classification
Design Topics
String Representation
iterator_range
class
Collection Traits
Sequence Traits
Find Algorithms
Replace Algorithms
Find Iterators & Split Algorithms
Exception Safety
Concepts
Definitions
Finder Concept
Formatter concept
Reference
Header <boost/algorithm/string/case_conv.hpp>
Header <boost/algorithm/string/classification.hpp>
Header <boost/algorithm/string/collection_traits.hpp>
Header <boost/algorithm/string/compare.hpp>
Header <boost/algorithm/string/concept.hpp>
Header <boost/algorithm/string/constants.hpp>
Header <boost/algorithm/string/erase.hpp>
Header <boost/algorithm/string/find.hpp>
Header <boost/algorithm/string/find_format.hpp>
Header <boost/algorithm/string/find_iterator.hpp>
Header <boost/algorithm/string/finder.hpp>
Header <boost/algorithm/string/formatter.hpp>
Header <boost/algorithm/string/iterator_range.hpp>
Header <boost/algorithm/string/predicate.hpp>
Header <boost/algorithm/string/regex.hpp>
Header <boost/algorithm/string/regex_find_format.hpp>
Header <boost/algorithm/string/replace.hpp>
Header <boost/algorithm/string/sequence_traits.hpp>
Header <boost/algorithm/string/split.hpp>
Header <boost/algorithm/string/std_containers_traits.hpp>
Header <boost/algorithm/string.hpp>
Header <boost/algorithm/string_regex.hpp>
Header <boost/algorithm/string/trim.hpp>
Rationale
Locales
Regular Expressions
Environment
Build
Examples
Tests
Portability
Credits
Acknowledgments
Boost.Threads
Overview
Introduction
Dangers
C++ Standard Library usage in multithreaded programs
Common guarantees for all Boost.Threads components
Design
Goals
Iterative Phases
Phase 1, Synchronization Primitives
Phase 2, Thread Management and Thread Specific Storage
The Next Phase
Concepts
Mutexes
Read/Write Mutexes
Rationale
Rationale for the Creation of Boost.Threads
Rationale for the Low Level Primitives Supported in Boost.Threads
Rationale for the Lock Design
Rationale for NonCopyable Thread Type
Rationale for not providing Event Variables
Reference
Header <boost/thread/barrier.hpp>
Header <boost/thread/condition.hpp>
Header <boost/thread/exceptions.hpp>
Header <boost/thread/mutex.hpp>
Header <boost/thread/once.hpp>
Header <boost/thread/recursive_mutex.hpp>
Header <boost/thread/read_write_mutex.hpp>
Header <boost/thread/thread.hpp>
Header <boost/thread/tss.hpp>
Header <boost/thread/xtime.hpp>
Frequently Asked Questions
Configuration
Library Defined Public Macros
Library Defined Implementation Macros
Build
Building the Boost.Threads Libraries
Testing the Boost.Threads Libraries
Implementation Notes
Win32
Release Notes
Boost 1.32.0
Acknowledgements
Boost.Tribool
Introduction
Tutorial
Basic usage
Renaming the indeterminate state
tribool
input/output
Reference
Header <boost/logic/tribool.hpp>
Header <boost/logic/tribool_fwd.hpp>
Header <boost/logic/tribool_io.hpp>
Testsuite
Acceptance tests
Boost.Variant
Introduction
Abstract
Motivation
Tutorial
Basic Usage
Advanced Topics
Reference
Concepts
Header <boost/variant.hpp>
Header <boost/variant/variant_fwd.hpp>
Header <boost/variant/variant.hpp>
Header <boost/variant/recursive_variant.hpp>
Header <boost/variant/recursive_wrapper.hpp>
Header <boost/variant/apply_visitor.hpp>
Header <boost/variant/get.hpp>
Header <boost/variant/bad_visit.hpp>
Header <boost/variant/static_visitor.hpp>
Header <boost/variant/visitor_ptr.hpp>
Design Overview
"Never-Empty" Guarantee
Miscellaneous Notes
Boost.Variant vs. Boost.Any
Portability
Troubleshooting
Acknowledgments
References
II. The BoostBook Documentation Format
Introduction
Getting Started
Configuring local DocBook XSL and DTD distributions
Configuring Apache FOP for PostScript/PDF Output
Configuring Doxygen for Documentation Extraction
Troubleshooting
Documenting libraries
Defining a BoostBook library
From HTML to BoostBook
Sectioning in BoostBook
Bringing Together a BoostBook Document
Linking in BoostBook
Reference
BoostBook element class-specialization
BoostBook element link-test
BoostBook element link-fail-test
BoostBook element typedef
BoostBook element static-constant
BoostBook element code
BoostBook element destructor
BoostBook element template-type-parameter
BoostBook element description
BoostBook element librarylist
BoostBook element library-reference
BoostBook element boostbook
BoostBook element union
BoostBook element inherit
BoostBook element template-varargs
BoostBook element source
BoostBook element function
BoostBook element postconditions
BoostBook element compile-test
BoostBook element method
BoostBook element snippet
BoostBook element constructor
BoostBook element namespace
BoostBook element if-fails
BoostBook element free-function-group
BoostBook element functionname
BoostBook element librarycategory
BoostBook element notes
BoostBook element data-member
BoostBook element specialization
BoostBook element union-specialization
BoostBook element throws
BoostBook element template-arg
BoostBook element method-group
BoostBook element requirement
BoostBook element precondition
BoostBook element paramtype
BoostBook element using-class
BoostBook element run-test
BoostBook element librarypurpose
BoostBook element copy-assignment
BoostBook element run-fail-test
BoostBook element template
BoostBook element compile-fail-test
BoostBook element returns
BoostBook element default
BoostBook element parameter
BoostBook element signature
BoostBook element overloaded-function
BoostBook element class
BoostBook element librarycategorydef
BoostBook element type
BoostBook element enumvalue
BoostBook element overloaded-method
BoostBook element programlisting
BoostBook element complexity
BoostBook element purpose
BoostBook element template-nontype-parameter
BoostBook element library
BoostBook element librarycategorylist
BoostBook element using-namespace
BoostBook element struct-specialization
BoostBook element struct
BoostBook element lib
BoostBook element enum
BoostBook element requires
BoostBook element effects
BoostBook element libraryname
BoostBook element libraryinfo
BoostBook element testsuite
BoostBook element header
BoostBook element rationale
III. Boost.Build v2 User Manual
How to use this document
Installation
Tutorial
Hello, world
Properties
Build Requests and Target Requirements
Project Attributes
Project Hierarchies
Libraries and Dependent Targets
Library dependencies
Static and shared libaries
Conditions and alternatives
Prebuilt targets
User documentation
Configuration
Writing Jamfiles
Overview
Main targets
Projects
Additional Jamfile rules
Project root
Build process
Build request
Building a main target
Building a project
Builtin target types
Programs
Libraries
Alias
Installing
Testing
Builtin features
Differences to Boost.Build V1
Configuration
Writing Jamfiles
Build process
Extender Manual
Introduction
Target types
Scanners
Tools and generators
Features
Main target rules
Toolset modules
Detailed reference
General information
Initialization
Command line
Writing Jamfiles
Generated headers
Build process
Alternative selection
Determining common properties
Features and properties
Build Variants
Property refinement
Conditional properties
Target identifiers and references
Generators
Selecting and ranking viable generators
Running generators
Selecting dependency graph
Property adjustment
Transformations cache
Frequently Asked Questions
I'm getting "Duplicate name of actual target" error. What does it mean?
Accessing environment variables
How to control properties order?
How to control the library order on Unix?
Can I get output of external program as a variable in a Jamfile?
How to get the project-root location?
How to change compilation flags for one file?
Why are the dll-path and hardcode-dll-paths properties useful?
Targets in site-config.jam
B. Boost.Build v2 architecture
Overview
The build layer
The tools layer
Targets
Dependency scanning

The Boost C++ Libraries

The Boost C++ Libraries

List of Tables
1. Construction and destruction related function objects.
2. Action types
3. Test 1CPU time of expressions with integer multiplication written as a lambda expression and as a traditional hand-coded function object class. The running times are expressed in arbitrary units.
4. Test 2CPU time of arithmetic expressions written as lambda expressions, as classic STL unnamed functions (using compose2, bind1st etc.) and as traditional hand-coded function object classes. Using BLL terminology, a and b are bound arguments in the expressions, and x is open. All variables were of types double. The running times are expressed in arbitrary units.
1. Case Conversion
2. Trimming
3. Predicates
4. Find algorithms
5. Erase/Replace
6. Split
7. Finders
8. Formatters
9. Find Iterators
10. Predicates
11. Collection Traits
12. Sequence Traits
13. Notation
14. Valid Expressions
15. Valid Expressions
1. Mutex Expressions
2. TryMutex Expressions
3. TimedMutex Expressions
4. Mutex Models
5. Lock Expressions
6. ScopedLock Expressions
7. TryLock Expressions
8. ScopedTryLock Expressions
9. TimedLock Expressions
10. ScopedTimedLock Expressions
11. Lock Models
12. ReadWriteMutex Expressions
13. TryReadWriteMutex Expressions
14. TimedReadWriteMutex Expressions
15. Mutex Models
16. ReadWriteLock Expressions
17. ScopedReadWriteLock Expressions
18. TryReadWriteLock Expressions
19. ScopedTryReadWriteLock Expressions
20. TimedReadWriteLock Expressions
21. ScopedTimedReadWriteLock Expressions
22. Lock Models
23. Supported Lock Types
24. Supported Lock Types
25. Supported Lock Types
26. Thread States
27. Thread States Transitions
28. Memory Visibility
1. BoostBook Output Formats
1. Converting HTML elements to BoostBook
1.
2.
1. Search paths for configuration files
2. Command line options

The Boost C++ Libraries

The Boost C++ Libraries

List of Examples
1. Throwing and handling exceptions in lambda expressions.
1. A Skeletal BoostBook Library

Part I. The Boost C++ Libraries

The Boost C++ Libraries

The Boost C++ Libraries

Table of Contents
Boost.Any
Introduction
Examples
Reference
ValueType
requirements
Header <boost/any.hpp>
Acknowledgements
Boost.Array
Introduction
Reference
Header <boost/array.hpp>
Design Rationale
For more information...
Acknowledgements
Boost.Date_Time
Conceptual
Motivation
Domain Concepts
Design Concepts
More Information
Gregorian
Date Class
Date Duration (aka Days)
Date Period
Date Iterators
Date Generators/Algorithms
Gregorian Calendar
Class day_clock
Posix Time
Ptime Class
Time Duration
Time Period
Time Iterators
Local Time Adjustment
Details
Calculations
Design Goals
Tradeoffs: Stability, Predictability, and Approximations
Serialization
Terminology
References
Build-Compiler Information
Tests
Change History
Acknowledgements
Examples
General Usage Examples
Dates as Strings
Days Alive
Days Between New Years
End of the Months
Localization Demonstration
Date Period Calculations
Print Holidays
Print Month
Month Adding
Time Math
Print Hours
Local to UTC Conversion
Time Periods
Library Reference
Date Time Reference
Gregorian Reference
Posix Time Reference
Boost.Function
Introduction
History & Compatibility Notes
Tutorial
Basic Usage
Free functions
Member functions
References to Function Objects
Comparing Boost.Function function objects
Reference
Definitions
Header <boost/function.hpp>
Header <boost/function_equal.hpp>
Frequently Asked Questions
Miscellaneous Notes
Boost.Function vs. Function Pointers
Performance
Combatting virtual function "bloat"
Acknowledgements
Testsuite
Acceptance tests
Negative tests
Boost.Lambda
In a nutshell
Getting Started
Installing the library
Conventions used in this document
Introduction
Motivation
Introduction to lambda expressions
Using the library
Introductory Examples
Parameter and return types of lambda functors
About actual arguments to lambda functors
Storing bound arguments in lambda functions
Lambda expressions in details
Placeholders
Operator expressions
Bind expressions
Overriding the deduced return type
Delaying constants and variables
Lambda expressions for control structures
Exceptions
Construction and destruction
Special lambda expressions
Casts, sizeof and typeid
Nesting STL algorithm invocations
Extending return type deduction system
Practical considerations
Performance
About compiling
Portability
Relation to other Boost libraries
Boost Function
Boost Bind
Contributors
Boost.Program_options
Introduction
Tutorial
Getting Started
Option Details
Multiple Sources
Library Overview
Options Description Component
Parsers Component
Storage Component
Annotated List of Symbols
How To
Non-conventional Syntax
Response Files
Winmain Command Line
Option Groups and Hidden Options
Custom Validators
Unicode Support
Design Discussion
Unicode Support
Acknowledgements
Reference
Header <boost/program_options/cmdline.hpp>
Header <boost/program_options/environment_iterator.hpp>
Header <boost/program_options/eof_iterator.hpp>
Header <boost/program_options/errors.hpp>
Header <boost/program_options/option.hpp>
Header <boost/program_options/options_description.hpp>
Header <boost/program_options/parsers.hpp>
Header <boost/program_options/positional_options.hpp>
Header <boost/program_options/value_semantic.hpp>
Header <boost/program_options/variables_map.hpp>
Header <boost/program_options/version.hpp>
Boost.Ref
Introduction
Reference
Header <boost/ref.hpp>
Acknowledgements
Boost.Signals
Introduction
Tutorial
How to Read this Tutorial
Compatibility Note
Hello, World! (Beginner)
Calling multiple slots
Passing values to and from slots
Connection Management
Linking against the Signals library
Reference
Header <boost/signal.hpp>
Header <boost/signals/slot.hpp>
Header <boost/signals/trackable.hpp>
Header <boost/signals/connection.hpp>
Header <boost/visit_each.hpp>
Header <boost/last_value.hpp>
Frequently Asked Questions
Design Overview
Type Erasure
connection
class
Slot Call Iterator
visit_each
function template
Design Rationale
Choice of Slot Definitions
User-level Connection Management
Combiner Interface
Connection Interfaces: += operator
trackable
rationale
Comparison with other Signal/Slot implementations
Testsuite
Acceptance tests
Boost String Algorithms Library
Introduction
Usage
First Example
Case conversion
Predicates and Classification
Trimming
Find algorithms
Replace Algorithms
Find Iterator
Split
Quick Reference
Algorithms
Finders and Formatters
Iterators
Classification
Design Topics
String Representation
iterator_range
class
Collection Traits
Sequence Traits
Find Algorithms
Replace Algorithms
Find Iterators & Split Algorithms
Exception Safety
Concepts
Definitions
Finder Concept
Formatter concept
Reference
Header <boost/algorithm/string/case_conv.hpp>
Header <boost/algorithm/string/classification.hpp>
Header <boost/algorithm/string/collection_traits.hpp>
Header <boost/algorithm/string/compare.hpp>
Header <boost/algorithm/string/concept.hpp>
Header <boost/algorithm/string/constants.hpp>
Header <boost/algorithm/string/erase.hpp>
Header <boost/algorithm/string/find.hpp>
Header <boost/algorithm/string/find_format.hpp>
Header <boost/algorithm/string/find_iterator.hpp>
Header <boost/algorithm/string/finder.hpp>
Header <boost/algorithm/string/formatter.hpp>
Header <boost/algorithm/string/iterator_range.hpp>
Header <boost/algorithm/string/predicate.hpp>
Header <boost/algorithm/string/regex.hpp>
Header <boost/algorithm/string/regex_find_format.hpp>
Header <boost/algorithm/string/replace.hpp>
Header <boost/algorithm/string/sequence_traits.hpp>
Header <boost/algorithm/string/split.hpp>
Header <boost/algorithm/string/std_containers_traits.hpp>
Header <boost/algorithm/string.hpp>
Header <boost/algorithm/string_regex.hpp>
Header <boost/algorithm/string/trim.hpp>
Rationale
Locales
Regular Expressions
Environment
Build
Examples
Tests
Portability
Credits
Acknowledgments
Boost.Threads
Overview
Introduction
Dangers
C++ Standard Library usage in multithreaded programs
Common guarantees for all Boost.Threads components
Design
Goals
Iterative Phases
Phase 1, Synchronization Primitives
Phase 2, Thread Management and Thread Specific Storage
The Next Phase
Concepts
Mutexes
Read/Write Mutexes
Rationale
Rationale for the Creation of Boost.Threads
Rationale for the Low Level Primitives Supported in Boost.Threads
Rationale for the Lock Design
Rationale for NonCopyable Thread Type
Rationale for not providing Event Variables
Reference
Header <boost/thread/barrier.hpp>
Header <boost/thread/condition.hpp>
Header <boost/thread/exceptions.hpp>
Header <boost/thread/mutex.hpp>
Header <boost/thread/once.hpp>
Header <boost/thread/recursive_mutex.hpp>
Header <boost/thread/read_write_mutex.hpp>
Header <boost/thread/thread.hpp>
Header <boost/thread/tss.hpp>
Header <boost/thread/xtime.hpp>
Frequently Asked Questions
Configuration
Library Defined Public Macros
Library Defined Implementation Macros
Build
Building the Boost.Threads Libraries
Testing the Boost.Threads Libraries
Implementation Notes
Win32
Release Notes
Boost 1.32.0
Acknowledgements
Boost.Tribool
Introduction
Tutorial
Basic usage
Renaming the indeterminate state
tribool
input/output
Reference
Header <boost/logic/tribool.hpp>
Header <boost/logic/tribool_fwd.hpp>
Header <boost/logic/tribool_io.hpp>
Testsuite
Acceptance tests
Boost.Variant
Introduction
Abstract
Motivation
Tutorial
Basic Usage
Advanced Topics
Reference
Concepts
Header <boost/variant.hpp>
Header <boost/variant/variant_fwd.hpp>
Header <boost/variant/variant.hpp>
Header <boost/variant/recursive_variant.hpp>
Header <boost/variant/recursive_wrapper.hpp>
Header <boost/variant/apply_visitor.hpp>
Header <boost/variant/get.hpp>
Header <boost/variant/bad_visit.hpp>
Header <boost/variant/static_visitor.hpp>
Header <boost/variant/visitor_ptr.hpp>
Design Overview
"Never-Empty" Guarantee
Miscellaneous Notes
Boost.Variant vs. Boost.Any
Portability
Troubleshooting
Acknowledgments
References
Documentation for some libraries is available in alternative formats: •HTML (tarred, gzipped)•PDF•Unix man pages•DocBook•XSL Formatting Objects
Libraries Listed Alphabetically
Libraries Listed Alphabetically
•
Any
- Safe, generic container for single values of different value types , from Kevlin Henney.
•
Array
- STL compliant container wrapper for arrays of constant size, from Nicolai Josuttis.
•
Bind
- Generalized binders for function/object/pointers and member functions, from Peter Dimov.
•
CRC
- Cyclic Redundancy Code, from Daryle Walker.
•
Call Traits
- Defines types for passing parameters, from John Maddock and Howard Hinnant.
•
Compatibility
- Help for non-conforming standard libraries, from Ralf Grosse-Kunstleve and Jens Maurer.
•
Compose
- Functional composition adapters for the STL, from Nicolai Josuttis.
•
Compressed Pair
- Empty member optimization, from John Maddock and Howard Hinnant.
•
Concept Check
- Tools for generic programming, from Jeremy Siek.
•
Config
- Helps boost library developers adapt to compiler idiosyncrasies; not intended for library users, from John Maddock, Beman Dawes, and Vesa Karvonen.
•
Conversion
- Numeric, polymorphic, and lexical casts, from Dave Abrahams and Kevlin Henney.
•
Date Time
- A set of facilities to ease programming with dates and times. , from Jeff Garland.
•
Dynamic Bitset
- A runtime sized version of std::bitset, from Jeremy Siek and Chuck Allison.
•
Filesystem
- Portable paths, iteration over directories, and other useful filesystem operations, from Beman Dawes.
•
Format
- Type-safe 'printf-like' format operations, from Samuel Krempp.
•
Function
- Function object wrappers for deferred calls or callbacks, from Douglas Gregor.
•
Functional
- Enhanced function object adaptors, from Mark Rodgers.
•
Graph
- Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.
•
I/O State Savers
- Save I/O state to prevent jumbled data, from Daryle Walker.
•
Integer
- Headers to ease dealing with integral types, from various authors.
•
Interval
- Extends the usual arithmetic functions to mathematical intervals, from Guillaume Melquiond, Hervé Brönnimann, and Sylvain Pion.
•
Iterator Adaptors
- Adapt a base type into a standard conforming iterator, from Dave Abrahams, Jeremy Siek, and John Potter.
•
Lambda
- Define small unnamed function objects at the actual call site, and more, from Jaakko Järvi.
•
MPL
- Template metaprogramming framework of compile-time algorithms, sequences and metafunction classes, from Aleksey Gurtovoy.
•
Math
- Several contributions in the domain of mathematics, from various authors.
•
Math/Common Factor
- Greatest common divisor and least common multiple, from Daryle Walker.
•
Math/Octonion
- Octonions, from Hubert Holin.
•
Math/Quaternion
- Quaternions, from Hubert Holin.
•
Math/Special Functions
- Mathematical special functions such as atanh, sinc, and sinhc, from Hubert Holin.
•
Mem_fn
- Generalized binders for member functions, from Peter Dimov.
•
Multi Array
- Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.
•
Operators
- Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.
•
Optional
- Discriminated-union wrapper for optional values, from Fernando Cacciola.
•
Pool
- Memory pool management, from Steve Cleary.
•
Preprocessor
- Preprocessor metaprogramming tools including repetition and recursion, from Vesa Karvonen and Paul Mensonides.
•
Program_options
- Facilities to obtain configuration data from command line, config files and other sources, from Vladimir Prus.
•
Property Map
- Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.
•
Python
- Reflects C++ classes and functions into Python, from Dave Abrahams.
•
Random
- A complete system for random number generation, from Jens Maurer.
•
Rational
- A rational number class, from Paul Moore.
•
Ref
- A utility library for passing references to generic functions, from Jaakko Järvi, Peter Dimov, Douglas Gregor, and Dave Abrahams.
•
Regex
- Regular expression library, from John Maddock.
•
Serialization
- Serialization of C++ objects for persistence and marshalling, from Robert Ramey.
•
Signals
- Managed signals & slots callback implementation, from Douglas Gregor.
•
Smart Pointer
- Five smart pointer class templates, from Greg Colvin, Beman Dawes, Peter Dimov, and Darin Adler.
•
Spirit
- LL parser framework represents parsers directly as EBNF grammars in inlined C++, from Joel de Guzman and team .
•
Static Assert
- Static assertions (compile time assertions), from John Maddock.
•
String Algorithms
- A set of generic string-related algorithms and utilities , from Pavol Droba.
•
Test
- Support for simple program testing, full unit testing, and for program execution monitoring, from Gennadiy Rozental.
•
Threads
- Portable C++ multi-threading, from William Kempf.
•
Timer
- Event timer, progress timer, and progress display classes, from Beman Dawes.
•
Tokenizer
- Break of a string or other character sequence into a series of tokens, from John Bandela.
•
Tribool
- Three-state boolean type, from Douglas Gregor.
•
Tuple
- Ease definition of functions returning multiple values, and more, from Jaakko Järvi.
•
Type Traits
- Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .
•
Utility
- Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
•
Variant
- Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.
•
uBLAS
- Basic linear algebra for dense, packed and sparse matrices, from Joerg Walter and Mathias Koch.
Libraries Listed by Category
Libraries Listed by Category
String and text processing
String and text processing
•
Format
- Type-safe 'printf-like' format operations, from Samuel Krempp.
•
Regex
- Regular expression library, from John Maddock.
•
String Algorithms
- A set of generic string-related algorithms and utilities , from Pavol Droba.
•
Tokenizer
- Break of a string or other character sequence into a series of tokens, from John Bandela.
Containers
Containers
•
Array
- STL compliant container wrapper for arrays of constant size, from Nicolai Josuttis.
•
Dynamic Bitset
- A runtime sized version of std::bitset, from Jeremy Siek and Chuck Allison.
•
Graph
- Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.
•
Multi Array
- Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.
•
Property Map
- Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.
•
Variant
- Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.
Iterators
Iterators
•
Graph
- Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.
•
Iterator Adaptors
- Adapt a base type into a standard conforming iterator, from Dave Abrahams, Jeremy Siek, and John Potter.
•
Operators
- Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.
•
Tokenizer
- Break of a string or other character sequence into a series of tokens, from John Bandela.
Algorithms
Algorithms
•
Graph
- Generic graph components and algorithms, from Jeremy Siek and University of Notre Dame Team.
•
Utility
- Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Function objects and higher-order programming
Function objects and higher-order programming
•
Bind
- Generalized binders for function/object/pointers and member functions, from Peter Dimov.
•
Compose
- Functional composition adapters for the STL, from Nicolai Josuttis.
•
Function
- Function object wrappers for deferred calls or callbacks, from Douglas Gregor.
•
Functional
- Enhanced function object adaptors, from Mark Rodgers.
•
Lambda
- Define small unnamed function objects at the actual call site, and more, from Jaakko Järvi.
•
Mem_fn
- Generalized binders for member functions, from Peter Dimov.
•
Ref
- A utility library for passing references to generic functions, from Jaakko Järvi, Peter Dimov, Douglas Gregor, and Dave Abrahams.
•
Signals
- Managed signals & slots callback implementation, from Douglas Gregor.
Generic programming
Generic programming
•
Call Traits
- Defines types for passing parameters, from John Maddock and Howard Hinnant.
•
Concept Check
- Tools for generic programming, from Jeremy Siek.
•
Operators
- Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.
•
Property Map
- Concepts defining interfaces which map key objects to value objects, from Jeremy Siek.
•
Static Assert
- Static assertions (compile time assertions), from John Maddock.
•
Type Traits
- Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .
Template metaprogramming
Template metaprogramming
•
MPL
- Template metaprogramming framework of compile-time algorithms, sequences and metafunction classes, from Aleksey Gurtovoy.
•
Static Assert
- Static assertions (compile time assertions), from John Maddock.
•
Type Traits
- Templates for fundamental properties of types, from John Maddock, Steve Cleary, and others .
Preprocessor metaprogramming
Preprocessor metaprogramming
•
Preprocessor
- Preprocessor metaprogramming tools including repetition and recursion, from Vesa Karvonen and Paul Mensonides.
Concurrent programming
Concurrent programming
•
Threads
- Portable C++ multi-threading, from William Kempf.
Math and numerics
Math and numerics
•
Integer
- Headers to ease dealing with integral types, from various authors.
•
Interval
- Extends the usual arithmetic functions to mathematical intervals, from Guillaume Melquiond, Hervé Brönnimann, and Sylvain Pion.
•
Math
- Several contributions in the domain of mathematics, from various authors.
•
Math/Common Factor
- Greatest common divisor and least common multiple, from Daryle Walker.
•
Math/Octonion
- Octonions, from Hubert Holin.
•
Math/Quaternion
- Quaternions, from Hubert Holin.
•
Math/Special Functions
- Mathematical special functions such as atanh, sinc, and sinhc, from Hubert Holin.
•
Multi Array
- Multidimensional containers and adaptors for arrays of contiguous data, from Ron Garcia.
•
Operators
- Templates ease arithmetic classes and iterators, from Dave Abrahams and Jeremy Siek.
•
Random
- A complete system for random number generation, from Jens Maurer.
•
Rational
- A rational number class, from Paul Moore.
•
uBLAS
- Basic linear algebra for dense, packed and sparse matrices, from Joerg Walter and Mathias Koch.
Correctness and testing
Correctness and testing
•
Concept Check
- Tools for generic programming, from Jeremy Siek.
•
Static Assert
- Static assertions (compile time assertions), from John Maddock.
•
Test
- Support for simple program testing, full unit testing, and for program execution monitoring, from Gennadiy Rozental.
Data structures
Data structures
•
Any
- Safe, generic container for single values of different value types , from Kevlin Henney.
•
Compressed Pair
- Empty member optimization, from John Maddock and Howard Hinnant.
•
Optional
- Discriminated-union wrapper for optional values, from Fernando Cacciola.
•
Program_options
- Facilities to obtain configuration data from command line, config files and other sources, from Vladimir Prus.
•
Tuple
- Ease definition of functions returning multiple values, and more, from Jaakko Järvi.
•
Variant
- Safe, generic, stack-based discriminated union container, from Eric Friedman and Itay Maman.
Input/Output
Input/Output
•
Format
- Type-safe 'printf-like' format operations, from Samuel Krempp.
•
I/O State Savers
- Save I/O state to prevent jumbled data, from Daryle Walker.
•
Serialization
- Serialization of C++ objects for persistence and marshalling, from Robert Ramey.
Inter-language support
Inter-language support
•
Python
- Reflects C++ classes and functions into Python, from Dave Abrahams.
Memory
Memory
•
Pool
- Memory pool management, from Steve Cleary.
•
Smart Pointer
- Five smart pointer class templates, from Greg Colvin, Beman Dawes, Peter Dimov, and Darin Adler.
•
Utility
- Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Parsing
Parsing
•
Spirit
- LL parser framework represents parsers directly as EBNF grammars in inlined C++, from Joel de Guzman and team .
Miscellaneous
Miscellaneous
•
CRC
- Cyclic Redundancy Code, from Daryle Walker.
•
Compressed Pair
- Empty member optimization, from John Maddock and Howard Hinnant.
•
Conversion
- Numeric, polymorphic, and lexical casts, from Dave Abrahams and Kevlin Henney.
•
Date Time
- A set of facilities to ease programming with dates and times. , from Jeff Garland.
•
Filesystem
- Portable paths, iteration over directories, and other useful filesystem operations, from Beman Dawes.
•
Optional
- Discriminated-union wrapper for optional values, from Fernando Cacciola.
•
Timer
- Event timer, progress timer, and progress display classes, from Beman Dawes.
•
Tribool
- Three-state boolean type, from Douglas Gregor.
•
Utility
- Class noncopyable plus checked_delete, checked_array_delete, next, prior function templates, plus base-from-member idiom, from Dave Abrahams and others .
Broken compiler workarounds
Broken compiler workarounds
•
Compatibility
- Help for non-conforming standard libraries, from Ralf Grosse-Kunstleve and Jens Maurer.
•
Config
- Helps boost library developers adapt to compiler idiosyncrasies; not intended for library users, from John Maddock, Beman Dawes, and Vesa Karvonen.

Boost.Any

Boost.Any

Boost.Any
Kevlin Henney
Copyright © 2001 Kevlin Henney
Introduction
Introduction
There are times when a generic (in the sense of general as opposed to template-based programming) type is needed: variables that are truly variable, accommodating values of many other more specific types rather than C++'s normal strict and static types. We can distinguish three basic kinds of generic type:
•
Converting types that can hold one of a number of possible value types, e.g. int and string, and freely convert between them, for instance interpreting 5 as "5" or vice-versa. Such types are common in scripting and other interpreted languages. boost::lexical_cast supports such conversion functionality.
•
Discriminated types that contain values of different types but do not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions.
•
Indiscriminate types that can refer to anything but are oblivious to the actual underlying type, entrusting all forms of access and interpretation to the programmer. This niche is dominated by void *, which offers plenty of scope for surprising, undefined behavior.
The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type. A similar design, offering more appropriate operators, can be used for a generalized function adaptor, any_function, a generalized iterator adaptor, any_iterator, and other object types that need uniform runtime treatment but support only compile-time template parameter conformance.
Examples
Examples
The following code demonstrates the syntax for using implicit conversions to and copying of any objects:
#include <list> #include <boost/any.hpp>

using boost::any_cast; typedef std::list<boost::any> many;

void append_int(many & values, int value) { boost::any to_append = value; values.push_back(to_append); }

void append_string(many & values, const std::string & value) { values.push_back(value); }

void append_char_ptr(many & values, const char * value) { values.push_back(value); }

void append_any(many & values, const boost::any & value) { values.push_back(value); }

void append_nothing(many & values) { values.push_back(boost::any()); }
The following predicates follow on from the previous definitions and demonstrate the use of queries on any objects:
bool is_empty(const boost::any & operand) { return operand.empty(); }

bool is_int(const boost::any & operand) { return operand.type() == typeid(int); }

bool is_char_ptr(const boost::any & operand) { try { any_cast<const char *>(operand); return true; } catch(const boost::bad_any_cast &) { return false; } }

bool is_string(const boost::any & operand) { return any_cast<std::string>(&operand); }

void count_all(many & values, std::ostream & out) { out << "#empty == " << std::count_if(values.begin(), values.end(), is_empty) << std::endl; out << "#int == " << std::count_if(values.begin(), values.end(), is_int) << std::endl; out << "#const char * == " << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl; out << "#string == " << std::count_if(values.begin(), values.end(), is_string) << std::endl; }
The following type, patterned after the OMG's Property Service, defines name-value pairs for arbitrary value types:
struct property { property(); property(const std::string &, const boost::any &);

std::string name; boost::any value; };

typedef std::list<property> properties;
The following base class demonstrates one approach to runtime polymorphism based callbacks that also require arbitrary argument types. The absence of virtual member templates requires that different solutions have different trade-offs in terms of efficiency, safety, and generality. Using a checked variant type offers one approach:
class consumer { public: virtual void notify(const any &) = 0; ... };
Reference
Reference
ValueType
requirements
Values are strongly informational objects for which identity is not significant, i.e. the focus is principally on their state content and any behavior organized around that. Another distinguishing feature of values is their granularity: normally fine-grained objects representing simple concepts in the system such as quantities.
As the emphasis of a value lies in its state not its identity, values can be copied and typically assigned one to another, requiring the explicit or implicit definition of a public copy constructor and public assignment operator. Values typically live within other scopes, i.e. within objects or blocks, rather than on the heap. Values are therefore normally passed around and manipulated directly as variables or through references, but not as pointers that emphasize identity and indirection.
The specific requirements on value types to be used in an any are:
•
A ValueType is CopyConstructible [20.1.3].
•
A ValueType is optionally Assignable [23.1]. The strong exception-safety guarantee is required for all forms of assignment.
•
The destructor for a ValueType upholds the no-throw exception-safety guarantee.
Header <boost/any.hpp>
namespace
boost { class bad_any_cast; class any; template<typename ValueType> ValueType any_cast(const any &); template<typename ValueType> const ValueType * any_cast(const any *); template<typename ValueType> ValueType * any_cast(any *); }
Class bad_any_cast
Class bad_any_cast -- The exception thrown in the event of a failed any_cast of an any value.
boost::bad_any_cast
class
bad_any_cast : public std::bad_cast { public: virtual const char * what() const; };
Description
Description
virtual
const
char
* what() const;
Class any
Class any -- A class whose instances can hold instances of any type that satisfies ValueType requirements.
boost::any
class
any { public: // construct/copy/destruct any(); any(const any &); template<typename ValueType> any(const ValueType &); any & operator=(const any &); template<typename ValueType> any & operator=(const ValueType &); ~any();

// modifiers
any
& swap(any &);

// queries
bool
empty
() const; const std::type_info & type() const; };
Description
Description
any construct/copy/destruct
any
construct/copy/destruct
1.
any();
Postconditions
this->empty()
2.
any(const any & other);
Effects
Copy constructor that copies content of other into new instance, so that any content is equivalent in both type and value to the content of other, or empty if other is empty.
Throws
May fail with a std::bad_alloc exception or any exceptions arising from the copy constructor of the contained type.
3.
template
<typename ValueType> any(const ValueType & value);
Effects
Makes a copy of value, so that the initial content of the new instance is equivalent in both type and value to value.
Throws
std::bad_alloc
or any exceptions arising from the copy constructor of the contained type.
4.
any
& operator=(const any & rhs);
Effects
Copies content of rhs into current instance, discarding previous content, so that the new content is equivalent in both type and value to the content of rhs, or empty if rhs.empty().
Throws
std::bad_alloc
or any exceptions arising from the copy constructor of the contained type. Assignment satisfies the strong guarantee of exception safety.
5.
template
<typename ValueType> any & operator=(const ValueType & rhs);
Effects
Makes a copy of rhs, discarding previous content, so that the new content of is equivalent in both type and value to rhs.
Throws
std::bad_alloc
or any exceptions arising from the copy constructor of the contained type. Assignment satisfies the strong guarantee of exception safety.
6.
~any();
Effects
Releases any and all resources used in management of instance.
Throws
Nothing.
any modifiers
any
modifiers
1.
any
& swap(any & rhs);
Effects
Exchange of the contents of *this and rhs.
Returns
*this
Throws
Nothing.
any queries
any
queries
1.
bool
empty() const;
Returns
true
if instance is empty, otherwise false.
Throws
Will not throw.
2.
const
std::type_info & type() const;
Returns
the typeid of the contained value if instance is non-empty, otherwise typeid(void).
Notes
Useful for querying against types known either at compile time or only at runtime.
Function any_cast
Function any_cast -- Custom keyword cast for extracting a value of a given type from an any.
boost::any_cast
template
<typename ValueType> ValueType any_cast(const any & operand); template<typename ValueType> const ValueType * any_cast(const any * operand); template<typename ValueType> ValueType * any_cast(any * operand);
Description
Description
Returns
If passed a pointer, it returns a similarly qualified pointer to the value content if successful, otherwise null is returned. If passed a value or reference, it returns a copy of the value content if successful.
Throws
Overloads taking an any pointer do not throw; the overload taking an any value or reference throws bad_any_cast if unsuccessful.
Rationale
The value/reference version returns a copy because the C++ keyword casts return copies.
Acknowledgements
Acknowledgements
Doug Gregor ported the documentation to the BoostBook format.

Boost.Array

Boost.Array

Boost.Array
Nicolai Josuttis
Copyright © 2001-2004 Nicolai M. Josuttis
Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.
Introduction
Introduction
The C++ Standard Template Library STL as part of the C++ Standard Library provides a framework for processing algorithms on different kind of containers. However, ordinary arrays don't provide the interface of STL containers (although, they provide the iterator interface of STL containers).
As replacement for ordinary arrays, the STL provides class std::vector. However, std::vector<> provides the semantics of dynamic arrays. Thus, it manages data to be able to change the number of elements. This results in some overhead in case only arrays with static size are needed.
In his book, Generic Programming and the STL, Matthew H. Austern introduces a useful wrapper class for ordinary arrays with static size, called block. It is safer and has no worse performance than ordinary arrays. In The C++ Programming Language, 3rd edition, Bjarne Stroustrup introduces a similar class, called c_array, which I (Nicolai Josuttis) present slightly modified in my book The C++ Standard Library - A Tutorial and Reference, called carray. This is the essence of these approaches spiced with many feedback from boost.
After considering different names, we decided to name this class simply array.
Note that this class is suggested to be part of the next Technical Report, which will extend the C++ Standard (see http://std.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1548.htm).
Class array fulfills most but not all of the requirements of "reversible containers" (see Section 23.1, [lib.container.requirements] of the C++ Standard). The reasons array is not an reversible STL container is because: •No constructors are provided.•Elements may have an undetermined initial value (see the section called “Design Rationale”).•swap() has no constant complexity.•size() is always constant, based on the second template argument of the type.•The container provides no allocator support.
It doesn't fulfill the requirements of a "sequence" (see Section 23.1.1, [lib.sequence.reqmts] of the C++ Standard), except that: •front() and back() are provided.•operator[] and at() are provided.
Reference
Reference
Header <boost/array.hpp>
namespace
boost { template<typename T, std::size_t N> class array; template<typename T, std::size_t N> void swap(array<T, N>&, array<T, N>&); template<typename T, std::size_t N> bool operator==(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator!=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator<(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator>(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator<=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator>=(const array<T, N>&, const array<T, N>&); }
Class template array
Class template array -- STL compliant container wrapper for arrays of constant size
boost::array
template
<typename T, std::size_t N> class array { public: // types typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type;

// static constants
static
const
size_type static_size = N;

// construct/copy/destruct
template
<typename U> array& operator=(const array<U, N>&);

// iterator support
iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const;

// reverse iterator support
reverse_iterator rbegin(); const_reverse_iterator rbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const;

// capacity
size_type size(); bool empty(); size_type max_size();

// element access
reference operator[](size_type); const_reference operator[](size_type) const; reference at(size_type); const_reference at(size_type) const; reference front(); const_reference front() const; reference back(); const_reference back() const; const T* data() const; T* c_array();

// modifiers
void
swap
(array<T, N>&); void assign(const T&);

T elems[N]; };

// specialized algorithms
template
<typename T, std::size_t N> void swap(array<T, N>&, array<T, N>&);

// comparisons
template
<typename T, std::size_t N> bool operator==(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator!=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator<(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator>(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator<=(const array<T, N>&, const array<T, N>&); template<typename T, std::size_t N> bool operator>=(const array<T, N>&, const array<T, N>&);
Description
Description
array construct/copy/destruct
array
construct/copy/destruct
1.
template
<typename U> array& operator=(const array<U, N>& other);
Effects
std::copy(rhs.begin(),rhs.end(), begin())
array iterator support
array
iterator support
1.
iterator begin(); const_iterator begin() const;
Returns
iterator for the first element
Throws
will not throw
2.
iterator end(); const_iterator end() const;
Returns
iterator for position after the last element
Throws
will not throw
array reverse iterator support
array
reverse iterator support
1.
reverse_iterator rbegin(); const_reverse_iterator rbegin() const;
Returns
reverse iterator for the first element of reverse iteration
2.
reverse_iterator rend(); const_reverse_iterator rend() const;
Returns
reverse iterator for position after the last element in reverse iteration
array capacity
array
capacity
1.
size_type size();
Returns
N
2.
bool
empty();
Returns
N==0
Throws
will not throw
3.
size_type max_size();
Returns
N
Throws
will not throw
array element access
array
element access
1.
reference operator[](size_type i); const_reference operator[](size_type i) const;
Requires
i < N
Returns
element with index i
Throws
will not throw.
2.
reference at(size_type i); const_reference at(size_type i) const;
Returns
element with index i
Throws
std::range_error
if i >= N
3.
reference front(); const_reference front() const;
Requires
N > 0
Returns
the first element
Throws
will not throw
4.
reference back(); const_reference back() const;
Requires
N > 0
Returns
the last element
Throws
will not throw
5.
const
T* data() const;
Returns
elems
Throws
will not throw
6.
T* c_array();
Returns
elems
Throws
will not throw
array modifiers
array
modifiers
1.
void
swap(array<T, N>& other);
Effects
std::swap_ranges(begin(), end(), other.begin())
Complexity
linear in N
2.
void
assign(const T& value);
Effects
std::fill_n(begin(), N, value)
array specialized algorithms
array
specialized algorithms
1.
template
<typename T, std::size_t N> void swap(array<T, N>& x, array<T, N>& y);
Effects
x.swap(y)
Throws
will not throw.
array comparisons
array
comparisons
1.
template
<typename T, std::size_t N> bool operator==(const array<T, N>& x, const array<T, N>& y);
Returns
std::equal(x.begin(), x.end(), y.begin())
2.
template
<typename T, std::size_t N> bool operator!=(const array<T, N>& x, const array<T, N>& y);
Returns
!(x == y)
3.
template
<typename T, std::size_t N> bool operator<(const array<T, N>& x, const array<T, N>& y);
Returns
std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end())
4.
template
<typename T, std::size_t N> bool operator>(const array<T, N>& x, const array<T, N>& y);
Returns
y < x
5.
template
<typename T, std::size_t N> bool operator<=(const array<T, N>& x, const array<T, N>& y);
Returns
!(y < x)
6.
template
<typename T, std::size_t N> bool operator>=(const array<T, N>& x, const array<T, N>& y);
Returns
!(x < y)
Design Rationale
Design Rationale
There was an important design tradeoff regarding the constructors: We could implement array as an "aggregate" (see Section 8.5.1, [dcl.init.aggr], of the C++ Standard). This would mean: •An array can be initialized with a brace-enclosing, comma-separated list of initializers for the elements of the container, written in increasing subscript order:boost::array<int,4> a = { { 1, 2, 3 } };Note that if there are fewer elements in the initializer list, then each remaining element gets default-initialized (thus, it has a defined value).
However, this approach has its drawbacks: passing no initializer list means that the elements have an indetermined initial value, because the rule says that aggregates may have: •No user-declared constructors.•No private or protected non-static data members.•No base classes.•No virtual functions.
Nevertheless, The current implementation uses this approach.
Note that for standard conforming compilers it is possible to use fewer braces (according to 8.5.1 (11) of the Standard). That is, you can initialize an array as follows:
boost::array
<int,4> a = { 1, 2, 3 };
I'd appreciate any constructive feedback. Please note: I don't have time to read all boost mails. Thus, to make sure that feedback arrives to me, please send me a copy of each mail regarding this class.
The code is provided "as is" without expressed or implied warranty.
For more information...
For more information...
To find more details about using ordinary arrays in C++ and the framework of the STL, see e.g.

The C++ Standard Library - A Tutorial and Reference by Nicolai M. Josuttis Addison Wesley Longman, 1999 ISBN 0-201-37926-0
Home Page of Nicolai Josuttis
Acknowledgements
Acknowledgements
Doug Gregor ported the documentation to the BoostBook format.
Concept reference
Concept reference
Copyright © 2001, 2002 Indiana University
Copyright © 2000, 2001 University of Notre Dame du Lac
Copyright © 2000 Jeremy SiekLie-Quan LeeAndrew Lumsdaine
Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc.
Copyright © 1994 Hewlett-Packard Company
This product includes software developed at the University of Notre Dame and the Pervasive Technology Labs at Indiana University. For technical information contact Andrew Lumsdaine at the Pervasive Technology Labs at Indiana University. For administrative and license questions contact the Advanced Research and Technology Institute at 351 West 10th Street. Indianapolis, Indiana 46202, phone 317-278-4100, fax 317-274-5902.
Some concepts based on versions from the MTL draft manual and Boost Graph and Property Map documentation, the SGI Standard Template Library documentation and the Hewlett-Packard STL, under the following license:
Concepts
Concepts
•
Assignable
•
InputIterator
•
OutputIterator
•
ForwardIterator
•
BidirectionalIterator
•
RandomAccessIterator
•
DefaultConstructible
•
CopyConstructible
•
EqualityComparable
•
LessThanComparable
•
SignedInteger
Concept Assignable
Concept Assignable
Assignable
Description
Description
Assignable types must have copy constructors, operator= for assignment, and the swap() function defined.
Refinement of
Refinement of
•
CopyConstructible
Notation
Notation
X
A type playing the role of assignable-type in the Assignable concept.
x
,
y
,
Objects of type X
Valid expressions
Valid expressions

Name
Expression
Type
Semantics
Assignment
x = y
X &
Require operator=
Swap
swap(x, y)
void
Require swap() function

Models
Models
•
int
See also
See also
•
CopyConstructible
Concept InputIterator
Concept InputIterator
InputIterator
Description
Description
An input iterator is an iterator that can read through a sequence of values. It is single-pass (old values of the iterator cannot be re-used), and read-only.
An input iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).
Refinement of
Refinement of
•
Assignable
•
DefaultConstructible
•
EqualityComparable
Associated types
Associated types
•
value_type
std::iterator_traits<Iter>::value_type
The value type of the iterator (not necessarily what *i returns)
•
difference_type
std::iterator_traits<Iter>::difference_type
The difference type of the iterator
•
category
std::iterator_traits<Iter>::iterator_category
The category of the iterator
Notation
Notation
Iter
A type playing the role of iterator-type in the InputIterator concept.
i
,
j
,
Objects of type Iter
x
Object of type value_type
Type expressions
Type expressions
Category tag
category must be derived from std::input_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible.
Value type copy constructibility
value_type must be a model of CopyConstructible.
Difference type properties
difference_type must be a model of SignedInteger.
Valid expressions
Valid expressions

Name
Expression
Type
Precondition
Semantics
Postcondition
Dereference
*i
Convertible to value_type
i
is incrementable (not off-the-end)
Preincrement
++i
Iter &
i
is incrementable (not off-the-end)
Postincrement
i++
i
is incrementable (not off-the-end)
Equivalent to (void)(++i)
i
is dereferenceable or off-the-end
Postincrement and dereference
*i++
Convertible to value_type
i
is incrementable (not off-the-end)
Equivalent to {value_type t = *i; ++i; return t;}
i
is dereferenceable or off-the-end

Complexity
Complexity
All iterator operations must take amortized constant time.
Models
Models
•
std::istream_iterator
See also
See also
•
DefaultConstructible
•
EqualityComparable
•
ForwardIterator
•
OutputIterator
Concept OutputIterator
Concept OutputIterator
OutputIterator
Description
Description
An output iterator is an iterator that can write a sequence of values. It is single-pass (old values of the iterator cannot be re-used), and write-only.
An output iterator represents a position in a (possibly infinite) sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).
Associated types
Associated types
•
value_type
std::iterator_traits<Iter>::value_type
The stated value type of the iterator (should be void for an output iterator that does not model some other iterator concept).
•
difference_type
std::iterator_traits<Iter>::difference_type
The difference type of the iterator
•
category
std::iterator_traits<Iter>::iterator_category
The category of the iterator
Notation
Notation
Iter
A type playing the role of iterator-type in the OutputIterator concept.
ValueType
A type playing the role of value-type in the OutputIterator concept.
i
,
j
,
Objects of type Iter
x
Object of type ValueType
Type expressions
Type expressions
The type Iter must be a model of Assignable.
The type ValueType must be a model of Assignable.
The type Iter must be a model of DefaultConstructible.
The type Iter must be a model of EqualityComparable.
Category tag
category must be derived from std::output_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible.
Difference type properties
difference_type must be a model of SignedInteger.
Valid expressions
Valid expressions

Name
Expression
Type
Precondition
Semantics
Postcondition
Dereference
*i
i
is incrementable (not off-the-end)
Dereference and assign
*i = x
i
is incrementable (not off-the-end)
*i
may not be written to again until it has been incremented.
Preincrement
++i
Iter &
i
is incrementable (not off-the-end)
Postincrement
i++
i
is incrementable (not off-the-end)
Equivalent to (void)(++i)
i
is dereferenceable or off-the-end
Postincrement, dereference, and assign
*i++ = x
i
is incrementable (not off-the-end)
Equivalent to {*i = t; ++i;}
i
is dereferenceable or off-the-end

Complexity
Complexity
All iterator operations must take amortized constant time.
Models
Models
•
std::ostream_iterator, ...,
•
std::insert_iterator, ...,
•
std::front_insert_iterator, ...,
•
std::back_insert_iterator, ...,
See also
See also
Concept ForwardIterator
Concept ForwardIterator
ForwardIterator
Description
Description
A forward iterator is an iterator that can read through a sequence of values. It is multi-pass (old values of the iterator can be re-used), and can be either mutable (data pointed to by it can be changed) or not mutable.
An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).
Refinement of
Refinement of
•
InputIterator
•
OutputIterator
Associated types
Associated types
•
value_type
std::iterator_traits<Iter>::value_type
The value type of the iterator
•
category
std::iterator_traits<Iter>::iterator_category
The category of the iterator
Notation
Notation
Iter
A type playing the role of iterator-type in the ForwardIterator concept.
i
,
j
,
Objects of type Iter
x
Object of type value_type
Type expressions
Type expressions
Category tag
category must be derived from std::forward_iterator_tag.
Valid expressions
Valid expressions

Name
Expression
Type
Precondition
Semantics
Postcondition
Dereference
*i
const-if-not-mutable value_type &
i
is incrementable (not off-the-end)
Member access
i->{member-name} (return type is pointer-to-object type)
const-if-not-mutable value_type *
i
is incrementable (not off-the-end)
Preincrement
++i
Iter &
i
is incrementable (not off-the-end)
Postincrement
i++
Iter
i
is incrementable (not off-the-end)
Equivalent to {Iter j = i; ++i; return j;}
i
is dereferenceable or off-the-end

Complexity
Complexity
All iterator operations must take amortized constant time.
Invariants
Invariants
Predecrement must return object
&i = &(++i)
Unique path through sequence
i == j
implies ++i == ++j
Models
Models
•
T *
•
std::hash_set<T>::iterator
See also
See also
•
BidirectionalIterator
Concept BidirectionalIterator
Concept BidirectionalIterator
BidirectionalIterator
Description
Description
A bidirectional iterator is an iterator that can read through a sequence of values. It can move in either direction through the sequence, and can be either mutable (data pointed to by it can be changed) or not mutable.
An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).
Refinement of
Refinement of
•
ForwardIterator
Associated types
Associated types
•
value_type
std::iterator_traits<Iter>::value_type
The value type of the iterator
•
category
std::iterator_traits<Iter>::iterator_category
The category of the iterator
Notation
Notation
Iter
A type playing the role of iterator-type in the BidirectionalIterator concept.
i
,
j
,
Objects of type Iter
x
Object of type value_type
Type expressions
Type expressions
Category tag
category must be derived from std::bidirectional_iterator_tag.
Valid expressions
Valid expressions

Name
Expression
Type
Precondition
Semantics
Postcondition
Predecrement
--i
Iter &
i
is incrementable (not off-the-end) and some dereferenceable iterator j exists such that i == ++j
Postdecrement
i--
Iter
Same as for predecrement
Equivalent to {Iter j = i; --i; return j;}
i
is dereferenceable or off-the-end

Complexity
Complexity
All iterator operations must take amortized constant time.
Invariants
Invariants
Predecrement must return object
&i = &(--i)
Unique path through sequence
i == j
implies --i == --j
Increment and decrement are inverses
++i; --i;
and --i; ++i; must end up with the value of i unmodified, if i both of the operations in the pair are valid.
Models
Models
•
T *
•
std::list<T>::iterator
See also
See also
•
RandomAccessIterator
Concept RandomAccessIterator
Concept RandomAccessIterator
RandomAccessIterator
Description
Description
A random access iterator is an iterator that can read through a sequence of values. It can move in either direction through the sequence (by any amount in constant time), and can be either mutable (data pointed to by it can be changed) or not mutable.
An iterator represents a position in a sequence. Therefore, the iterator can point into the sequence (returning a value when dereferenced and being incrementable), or be off-the-end (and not dereferenceable or incrementable).
Refinement of
Refinement of
•
BidirectionalIterator
•
LessThanComparable
Associated types
Associated types
•
value_type
std::iterator_traits<Iter>::value_type
The value type of the iterator
•
category
std::iterator_traits<Iter>::iterator_category
The category of the iterator
•
difference_type
std::iterator_traits<Iter>::difference_type
The difference type of the iterator (measure of the number of steps between two iterators)
Notation
Notation
Iter
A type playing the role of iterator-type in the RandomAccessIterator concept.
i
,
j
,
Objects of type Iter
x
Object of type value_type
n
Object of type difference_type
int_off
Object of type int
Type expressions
Type expressions
Category tag
category must be derived from std::random_access_iterator_tag.
Valid expressions
Valid expressions

Name
Expression
Type
Semantics
Motion
i += n
Iter &
Equivalent to applying i++n times if n is positive, applying i---n times if n is negative, and to a null operation if n is zero.
Motion (with integer offset)
i += int_off
Iter &
Equivalent to applying i++n times if n is positive, applying i---n times if n is negative, and to a null operation if n is zero.
Subtractive motion
i -= n
Iter &
Equivalent to i+=(-n)
Subtractive motion (with integer offset)
i -= int_off
Iter &
Equivalent to i+=(-n)
Addition
i + n
Iter
Equivalent to {Iter j = i; j += n; return j;}
Addition with integer
i + int_off
Iter
Equivalent to {Iter j = i; j += n; return j;}
Addition (count first)
n + i
Iter
Equivalent to i + n
Addition with integer (count first)
int_off + i
Iter
Equivalent to i + n
Subtraction
i - n
Iter
Equivalent to i + (-n)
Subtraction with integer
i - int_off
Iter
Equivalent to i + (-n)
Distance
i - j
difference_type
The number of times i must be incremented (or decremented if the result is negative) to reach j. Not defined if j is not reachable from i.
Element access
i[n]
const-if-not-mutable value_type &
Equivalent to *(i + n)
Element access with integer index
i[int_off]
const-if-not-mutable value_type &
Equivalent to *(i + n)

Complexity
Complexity
All iterator operations must take amortized constant time.
Models
Models
•
T *
•
std::vector<T>::iterator
•
std::vector<T>::const_iterator
•
std::deque<T>::iterator
•
std::deque<T>::const_iterator
See also
See also
•
LessThanComparable
Concept DefaultConstructible
Concept DefaultConstructible
DefaultConstructible
Description
Description
DefaultConstructible objects only need to have a default constructor.
Notation
Notation
X
A type playing the role of default-constructible-type in the DefaultConstructible concept.
Valid expressions
Valid expressions

Name
Expression
Type
Semantics
Construction
X()
X
Construct an instance of the type with default parameters.

Models
Models
•
int
•
std::vector<double>
Concept CopyConstructible
Concept CopyConstructible
CopyConstructible
Description
Description
Copy constructible types must be able to be constructed from another member of the type.
Notation
Notation
X
A type playing the role of copy-constructible-type in the CopyConstructible concept.
x
,
y
,
Objects of type X
Valid expressions
Valid expressions

Name
Expression
Type
Semantics
Copy construction
X(x)
X
Require copy constructor.

Models
Models
•
int
Concept EqualityComparable
Concept EqualityComparable
EqualityComparable
Description
Description
Equality Comparable types must have == and != operators.
Notation
Notation
X
A type playing the role of comparable-type in the EqualityComparable concept.
x
,
y
,
Objects of type X
Valid expressions
Valid expressions

Name
Expression
Type
Equality test
x == y
Convertible to bool
Inequality test
x != y
Convertible to bool

Models
Models
•
int
•
std::vector<int>
Concept LessThanComparable
Concept LessThanComparable
LessThanComparable
Description
Description
LessThanComparable types must have <, >, <=, and >= operators.
Notation
Notation
X
A type playing the role of comparable-type in the LessThanComparable concept.
x
,
y
,
Objects of type X
Valid expressions
Valid expressions

Name
Expression
Type
Semantics
Less than
x < y
Convertible to bool
Determine if one value is less than another.
Less than or equal
x <= y
Convertible to bool
Determine if one value is less than or equal to another.
Greater than
x > y
Convertible to bool
Determine if one value is greater than another.
Greater than or equal to
x >= y
Convertible to bool
Determine if one value is greater than or equal to another.

Models
Models
•
int
Concept SignedInteger
Concept SignedInteger
SignedInteger
Refinement of
Refinement of
•
CopyConstructible
•
Assignable
•
DefaultConstructible
•
EqualityComparable
•
LessThanComparable
Notation
Notation
T
A type playing the role of integral-type in the SignedInteger concept.
x
,
y
,
z
,
Objects of type T
a
,
b
,
Objects of type int
Type expressions
Type expressions
Conversion to int
T must be convertible to int.
Valid expressions
Valid expressions

Name
Expression
Type
Conversion from int
T(a)
T
Preincrement
++x
T &
Predecrement
--x
T &
Postincrement
x++
T
Postdecrement
x--
T
Sum
x + y
T
Sum with int
x + a
T
Sum-assignment
x += y
T &
Sum-assignment with int
x += a
T &
Difference
x - y
T
Difference with int
x - a
T
Product
x * y
T
Product with int
x * a
T
Product-assignment with int
x *= a
T &
Product with int on left
a * x
T
Quotient
x / y
T
Quotient with int
x / a
T
Right-shift
x >> y
T
Right-shift with int
x >> a
T
Right-shift-assignment with int
x >>= a
T &
Less-than comparison
x < y
Convertible to bool
Less-than comparison with int
x < a
Convertible to bool
Less-than comparison with size_t
x < boost::sample_value < std::size_t >()
Convertible to bool
Greater-than comparison
x > y
Convertible to bool
Greater-than comparison with int
x > a
Convertible to bool
Less-than-or-equal comparison
x <= y
Convertible to bool
Less-than-or-equal comparison with int
x <= a
Convertible to bool
Greater-than-or-equal comparison
x >= y
Convertible to bool
Greater-than-or-equal comparison with int
x >= a
Convertible to bool
Greater-than-or-equal comparison with int on left
a >= x
Convertible to bool
Equality comparison
x == y
Convertible to bool
Equality comparison with int
x == a
Convertible to bool

See also
See also

Boost.Date_Time

Boost.Date_Time

Boost.Date_Time
Jeff Garland
Copyright © 2001-2004 CrystalClear Software, Inc
Subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
A set of date-time libraries based on generic programming concepts.
Conceptual
Conceptual
Motivation
The motivation for this library comes from working with and helping build several date-time libraries on several projects. Date-time libraries provide fundamental infrastructure for most development projects. However, most of them have limitations in their ability to calculate, format, convert, or perform some other functionality. For example, most libraries do not correctly handle leap seconds, provide concepts such as infinity, or provide the ability to use high resolution or network time sources. These libraries also tend to be rigid in their representation of dates and times. Thus customized policies for a project or subproject are not possible.
Programming with dates and times should be almost as simple and natural as programming with strings and integers. Applications with lots of temporal logic can be radically simplified by having a robust set of operators and calculation capabilities. Classes should provide the ability to compare dates and times, add lengths or time durations, retrieve dates and times from clocks, and work naturally with date and time intervals.
Another motivation for development of the library was to apply modern C++ library design techniques to the date-time domain. Really to build a framework for the construction of building temporal types. For example, by providing iterators and traits classes to control fundamental properties of the library. To the authors knowledge this library is the only substantial attempt to apply modern C++ to a date-time library.
Domain Concepts
The date time domain is rich in terminology and problems. The following is a brief introduction to the concepts you will find reflected in the library.
The library supports 3 basic temporal types: •Time Point -- Specifier for a location in the time continuum. •Time Duration -- A length of time unattached to any point on the time continuum. •Time Interval -- A duration of time attached to a specific point in the time continuum. Also known as a time period.
Each of these temporal types has a Resolution which is defined by the smallest representable duration. A Time system provides all these categories of temporal types as well as the rules for labeling and calculating with time points. Calendar Systems are simply time systems with a maximum resolution of one day. The Gregorian system is the most widely used calendar system today (the ISO system is basically a derivative of this). However, there are many other calendar systems as well. UTC (Coordinated Universal Time) is a widely used civil time system. UTC is adjusted for earth rotation at longitude 0 by the use of leap seconds (This is not predictable, only as necessary). Most local time systems are based on UTC but are also adjusted for earth rotation so that daylight hours are similar everywhere. In addition, some local times include daylight savings time (DST) adjustments to shift the daylight hours during the summer.
A Clock Device is software component (tied to some hardware) that provides the current date or time with respect to a time system. A clock can measure the current time to a known resolution which may be higher or lower than a particular time representation.
The library provides support for calculating with dates and times. However, time calculations are not quite the same as calculating with integers. If you are serious about the accuracy of your time calculations need to read about Stability, Predictability, and Approximations.
•
Basic Terminology
•
Calculations
•
Stability, Predictability, and Approximations
•
References
Design Concepts
A large part of the genesis of this library has been the observation that few date-time libraries are built in a fashion that allows customization and extension. A typical example, the calendar logic is built directly into the date class. Or the clock retrieval functions are built directly into the time class. These design decisions usually make it impossible to extend or change the library behavior. At a more fundamental level, there are usually assumptions about the resolution of time representation or the gregorian calendar.
Often times, the result is that a project must settle for a less than complete library because of a requirement for high resolution time representation or other assumptions that do not match the implementation of the library. This is extremely unfortunate because development of a library of this sort is far from a trivial task.
While the design is far from perfect the current design is far more flexible than any date-time library the author is aware of. It is expected that the various aspects of extensibility will be better documented in future versions. Information about the design goals of the library is summarized here.
More Information
The design of the library is currently being evolved using Wiki and email discussions. You can find more information at: •Boost Wiki GDTL Start Page•Full Doxygen Reference Manual
Gregorian
Gregorian
Gregorian Date System
Gregorian Date System
Introduction
-- Usage Examples
Introduction
Introduction
The gregorian date system provides a date programming system based the Gregorian Calendar. The first introduction of the Gregorian calendar was in 1582 to fix an error in the Julian Calendar. However, many local jurisdictions did not adopt this change until much later. Thus there is potential confusion with historical dates.
The implemented calendar is a "propleptic Gregorian calendar" which extends dates back prior to the Gregorian Calendar's first adoption in 1582. The current implementation supports dates in the range 1400-Jan-01 to 10000-Jan-01. Many references will represent dates prior to 1582 using the Julian Calendar, so caution is in order if accurate calculations are required on historic dates. See Calendrical Calculations by Reingold & Dershowitz for more details. Date information from Calendrical Calculations has been used to cross-test the correctness of the Gregorian calendar implementation.
All types for the gregorian system are found in namespace boost::gregorian. The library supports a convenience header boost/date_time/gregorian/gregorian_types.hpp that will include all the classes of the library with no input/output dependency. Another header boost/date_time/gregorian/gregorian.hpp will include the types and the input/output code.
The class boost::gregorian::date is the primary temporal type for users. If you are interested in learning about writing programs do specialized date calculations such as finding the "first sunday in april" see the date generators and algorithms page.
Usage Examples
Usage Examples

Example
Description
Days Alive
Days Till New Year
Simple date arithmetic. Retrieve current day from clock.
Dates as strings
Simple parsing and formatting of dates from/to strings
Date Period Calculations
See if a date is in a set of date periods (eg: is it a holiday/weekend)
Print a month
Small utility program which prints out all the days in a month from command line. Need to know if 1999-Jan-1 was a Friday or a Saturday? This program shows how to do it.
Print Holidays
Uses date generators to convert abstract specification into concrete set of dates.

Date Class
Introduction
-- Header -- Construction -- Construct from String -- Construct from Clock -- Accessors -- Convert to String -- Operators Introduction Introduction The class boost::gregorian::date is the primary interface for date programming. In general, the date class is immutable once constructed although it does allow assignment. Other techniques for creating dates include date iterators and date algorithms or generators. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
date(greg_year year, greg_month month, greg_day day)
Construct from parts of date. Throws bad_year, bad_day_of_month, or bad_day_month (derivatives of std::out_of_range) if the year, month or day are out of range.
date d(2002,Jan,10)
date(date d)
Copy constructor
date d1(d)
date(special_values sv)
Constructor for infinities, not-a-date-time, max_date_time, and min_date_time
date d1(neg_infin); date d2(pos_infin); date d3(not_a_date_time); date d4(max_date_time); date d5(min_date_time);
date;
Default constructor. Creates a date object initialized to not_a_date_time. NOTE: this constructor can be disabled by defining DATE_TIME_NO_DEFAULT_CONSTRUCTOR (see compiler_config.hpp)
date d; // d => not_a_date_time

Construct from String
Construct from String

Syntax
Description
Example
date from_string(const std::string&)
From delimited date string where with order year-month-day eg: 2002-1-25
std::string ds("2002/1/25"); date d(from_string(ds))
date from_undelimited_string(const std::string&)
From iso type date string where with order year-month-day eg: 20020125
std::string ds("20020125"); date d(from_undelimited_string(ds))

Construct from Clock
Construct from Clock

Syntax
Description
Example
day_clock::local_day()
Get the local day based on the time zone settings of the computer.
date d(day_clock::local_day())
day_clock::universal_day()
Get the UTC day.
date d(day_clock::universal_day())

Accessors
Accessors

Syntax
Description
Example
greg_year year() const
Get the year part of the date.
date d(2002,Jan,10); d.year() --> 2002;
greg_month month() const
Get the month part of the date.
date d(2002,Jan,10); d.month() --> 1;
greg_day day() const
Get the day part of the date.
date d(2002,Jan,10); d.day() --> 10;
greg_ymd year_month_day() const
Return a year_month_day struct. More efficient when all 3 parts of the date are needed.
date d(2002,Jan,10); date::ymd_type ymd = d.year_month_day(); ymd.year --> 2002, ymd.month --> 1, ymd.day --> 10
greg_day_of_week day_of_week() const
Get the day of the week (eg: Sunday, Monday, etc.
date d(2002,Jan,10); d.day() --> Thursday;
bool is_infinity() const
Returns true if date is either positive or negative infinity
date d(pos_infin); d.is_infinity() --> true;
bool is_neg_infinity() const
Returns true if date is negative infinity
date d(neg_infin); d.is_neg_infinity() --> true;
bool is_pos_infinity() const
Returns true if date is positive infinity
date d(neg_infin); d.is_pos_infinity() --> true;
bool is_not_a_date() const
Returns true if value is not a date
date d(not_a_date_time); d.is_not_a_date() --> true;
long modjulian_day() const
Returns the modified julian day for the date.
long julian_day() const
Returns the julian day for the date.
int week_number() const
Returns the ISO 8601 week number for the date.

Convert to String
Convert to String

Syntax
Description
Example
std::string to_simple_string(date d)
To YYYY-mmm-DD string where mmm 3 char month name.
2002-Jan-01
std::string to_iso_string(date d)
To YYYYMMDD where all components are integers.
20020131
std::string to_iso_extended_string(date d)
To YYYY-MM-DD where all components are integers.
2002-01-31

Operators
Operators

Syntax
Description
Example
operator<<
Stream output operator
date d(2002,Jan,1) std::cout << d << std::endl;
operator==, operator!=, operator>, operator< operator>=, operator<=
A full complement of comparison operators
d1 == d2, etc
date operator+(date_duration) const
Return a date adding a day offset
date d(2002,Jan,1); date_duration dd(1); date d2 = d + dd;
date operator-(date_duration) const
Return a date by adding a day offset
date d(2002,Jan,1); date_duration dd(1); date d2 = d - dd;
date_duration operator-(date) const
Return a date duration by subtracting two dates
date d1(2002,Jan,1); date d2(2002,Jan,2); date_duration dd = d2-d1;

top
Date Duration (aka Days)
Introduction
-- Header -- Construction -- Operators Introduction Introduction As of version 1_32 the date_duration class has been typdefed as days in the boost::gregorian namespace. Throughout the examples you will find days used instead of date_duration. The class boost::gregorian::date_duration is a simple day count used for arithmetic with gregorian::date. A duration can be either positive or negative. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
date_duration(long)
Create a duration count.
date_duration dd(3); //3 days

Accessors
Accessors

Syntax
Description
Example
long days() const
Get the day count.
date_duration dd(3); dd.days() --> 3
bool is_negative() const
True if number of days is less than zero.
date_duration dd(-1); dd.is_negative() --> true
static date_duration unit()
Return smallest possible unit of duration type.
date_duration::unit() --> date_duration(1)

Operators
Operators

Syntax
Description
Example
operator==, operator!=, operator>, operator< operator>=, operator<=
A full complement of comparison operators
dd1 == dd2, etc
date_duration operator+(date_duration) const
Add date durations.
date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 + dd2;
date_duration operator-(date_duration) const
Subtract durations.
date_duration dd1(3); date_duration dd2(5); date_duration dd3 = dd1 - dd2;

top
Date Period
Introduction
-- Header -- Construction -- Accessors -- Convert to String -- Operators Introduction Introduction The class boost::gregorian::date_period provides direct representation for ranges between two dates. Periods provide the ability to simplify some types of calculations by simplifying the conditional logic of the program. For example, testing if a date is within an irregular schedule such as a weekend or holiday can be accomplished using collections of date periods. This is facilitated by several methods that allow evaluation if a date_period intersects with another date period, and to generate the period resulting from the intersection. The period calculation example provides an example of this. Date periods used in combination with infinity values have the ability to represent complex concepts such as 'until further notice'. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
date_period(date begin, date end)
Create a period as [begin, end). If last is <= begin then the period will be defined as null.
date_period dp(date(2002,Jan,10), date(2002,Jan,12));
date_period(date start, date_duration len)
Create a period as [begin, begin+len). If len is <= zero then the period will be defined as null.
date_period dp(date(2002,Jan,10), date_duration(2));
date_period(date_period rhs)
Copy constructor
date_period dp1(dp)

Accessors
Accessors

Syntax
Description
Example
date begin() const
Return first day of period.
date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.begin() --> 2002-Jan-01
date last() const
Return last date in the period
date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.last() --> 2002-Jan-09
date end() const
Return one past the last in period
date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.end() --> 2002-Jan-10
date_duration length() const
Return the length of the date_period
date_period dp(date(2002,Jan,1), date_duration(2)); dp.length() --> 2
bool is_null() const
True if period is not well formed. eg: start less than end
date_period dp(date(2002,Jan,10), date(2002,Jan,1)); dp.begin() --> true
bool contains(date) const
True if date is within the period
date_period dp(date(2002,Jan,1), date(2002,Jan,10)); dp.contains(date(2002,Jan,2)) --> true
bool contains(date_period) const
True if date period is within the period
date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp1.contains(dp2) --> true dp2.contains(dp1) --> false
bool intersects(date_period) const
True if periods overlap
date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp2.intersects(dp1) --> true
date_period intersection(date_period) const
Calculate the intersection of 2 periods. Null if no intersection.
date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,2), date(2002,Jan,3)); dp2.intersection(dp1) --> dp2
date_period is_adjacent(date_period) const
Check if two periods are adjacent, but not overlapping.
date_period dp1(date(2002,Jan,1), date(2002,Jan,3)); date_period dp2(date(2002,Jan,3), date(2002,Jan,10)); dp2.is_adjacent(dp1) --> true
date_period is_after(date) const
Determine the period is after a given date.
date_period dp1(date(2002,Jan,10), date(2002,Jan,30)); date d(2002,Jan,3); dp1.is_after(d) --> true
date_period is_before(date) const
Determine the period is before a given date.
date_period dp1(date(2002,Jan,1), date(2002,Jan,3)); date d(2002,Jan,10); dp1.is_before(d) --> true
date_period merge(date_period) const
Returns union of two periods. Null if no intersection.
date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); date_period dp2(date(2002,Jan,9), date(2002,Jan,31)); dp2.merge(dp1) --> 2002-Jan-01/2002-Jan-31
date_period span(date_period) const
Combines two periods and any gap between them such that start = min(p1.start, p2.start) and end = max(p1.end , p2.end)
date_period dp1(date(2002,Jan,1), date(2002,Jan,5)); date_period dp2(date(2002,Jan,9), date(2002,Jan,31)); dp2.hull(dp1) --> 2002-Jan-01/2002-Jan-31
date_period shift(date_duration)
Add duration to both start and end.
date_period dp1(date(2002,Jan,1), date(2002,Jan,10)); dp1.shift(date_duration(1)); --> 2002-Jan-02/2002-Jan-11

Convert to String
Convert to String

Syntax
Description
Example
std::string to_simple_string(date_period dp)
To [YYYY-mmm-DD/YYYY-mmm-DD] string where mmm is 3 char month name.
[2002-Jan-01/2002-Jan-31]

Operators
Operators

Syntax
Description
Example
operator<<
ostream operator for date_period. Uses facet to format time points. Typical output: [2002-Jan-01/2002-Jan-31].
std::cout << dp << std::endl;
operator==, operator!=, operator>, operator<
A full complement of comparison operators
dp1 == dp2, etc
operator<
True if dp1.end() less than dp2.begin()
dp1 < dp2, etc
operator>
True if dp1.begin() greater than dp2.end()
dp1 > dp2, etc

top
Date Iterators
Introduction
-- Header -- Overview Introduction Introduction Date iterators provide a standard mechanism for iteration through dates. Date iterators are a model of Input Iterator and can be used to populate collections with dates and other date generation tasks. For example, the print month example iterates through all the days in a month and prints them. All of the iterators here derive from boost::gregorian::date_iterator. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Overview Overview

Class
Construction Parameters
Description
date_iterator
Common base class for all day level iterators.
day_iterator
date start_date, int day_count=1
Iterate day_count days at a time.
week_iterator
date start_date, int week_offset=1
Iterate week_offset weeks at a time.
month_iterator
date start_date, int month_offset=1
Iterate month_offset months. There are special rules for handling the end of the month. These are: if start date is last day of the month, always adjust to last day of the month. If date is beyond the end of the month (eg: jan 31 + 1 month) adjust back to end of month.
year_iterator
date start_date, int year_offset=1
Iterate year_offset years. The year_iterator will always land on the day of the date parameter except when date is Feb 28 in a non-leap year. In this case the iterator will return Feb 29 for leap years (eg: 2003-Feb-28, 2004-Feb-29, 2005-Feb-28).

top
Date Generators/Algorithms
Date Generators/Algorithms
Date Generators/Algorithms
Introduction
-- Header -- Class Overview -- Function Overview Introduction Introduction Date algorithms or generators are tools for generating other dates or schedules of dates. A generator function starts with some part of a date such as a month and day and is supplied another part to then generate a concrete date. This allows the programmer to represent concepts such as "The first Sunday in February" and then create a concrete set of dates when provided with one or more years. Note: As of boost version 1_31_0, date generator names have been changed. Old names are still available but are no longer documented and may someday be deprecated Also provided are stand-alone functions for generating a date, or calculation a duration of days. These functions take a date object and a weekday object as parameters. All date generator classes and functions are in the boost::gregorian namespace. The print holidays example shows a detailed usage example. Header Header #include "boost/date_time/date_generators.hpp" Overview Overview

Class
Construction Parameters
get_date Parameter
Description
Example
year_based_generator
abstract base class
greg_year year
A unifying date_generator base type for: partial_date, nth_day_of_the_week_in_month, first_day_of_the_week_in_month, and last_day_of_the_week_in_month
The print holidays example shows a detailed usage example.
last_day_of_the_week_in_month
greg_weekday or weekday, greg_month or month
greg_year or year
Calculate something like last Monday of January
last_day_of_the_week_in_month lwdm(Monday,Jan); date d = lwdm.get_date(2002);//2002-Jan-28
first_day_of_the_week_in_month
greg_weekday or weekday, greg_month or month
greg_year or year
Calculate something like first Monday of January
first_day_of_the_week_in_month fdm(Monday,Jan); date d = fdm.get_date(2002);//2002-Jan-07
partial_date
greg_day, greg_month or month
greg_year
Generates a date by applying the year to the given month and day.
partial_date pd(1,Jan); date d = pd.get_date(2002);//2002-Jan-01
first_day_of_the_week_after
greg_weekday or weekday
date
Calculate something like First Sunday after Jan 1,2002
first_day_of_the_week_after fdaf(Monday); date d = fdaf.get_date(date(2002,Jan,1));//2002-Jan-07
first_day_of_the_week_before
greg_weekday or weekday
date
Calculate something like First Monday before Feb 1,2002
first_day_of_the_week_before fdbf(Monday); date d = fdbf.get_date(date(2002,Feb,1));//2002-Jan-28

Function Overview
Function Overview

Function Prototype
Description
Example
days
days_until_weekday (const date&, const greg_weekday&)
Calculates the number of days from given date until given weekday.
date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); days_until_weekday(d, gw); // 3 days
days
days_before_weekday (const date&, const greg_weekday&)
Calculates the number of day from given date to previous given weekday.
date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); days_before_weekday(d, gw); // 4 days
date
next_weekday (const date&, const greg_weekday&)
Generates a date object representing the date of the following weekday from the given date.
date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); next_weekday(d, gw); // 2004-Jun-4
date
previous_weekday (const date&, const greg_weekday&)
Generates a date object representing the date of the previous weekday from the given date.
date d(2004,Jun,1); // Tuesday greg_weekday gw(Friday); previous_weekday(d, gw); // 2004-May-28

top
Gregorian Calendar
Introduction
-- Header -- Functions Introduction Introduction The class boost::gregorian::gregorian_calendar implements the functions necessary to create the gregorian date system. It converts to the year-month-day form of a date to a day number representation and back. For most purposes this class is simply accessed by gregorian::date and is not used directly by the user. However, there are useful functions that might be of use such as the end_of_month_day function. The print month example demonstrates this. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Functions Functions

Syntax
Description
Example
static short day_of_week(ymd_type)
Return the day of the week (0==Sunday, 1==Monday, etc)
See also gregorian::date day_of_week
static date_int_type day_number(ymd_type)
Convert a ymd_type into a day number. The day number is an absolute number of days since the epoch start.
static short end_of_month_day(year_type, month_type)
Given a year and month determine the last day of the month.
static ymd_type from_day_number(date_int_type)
Convert a day number to a ymd struct.
static bool is_leap_year(year_type)
Returns true if specified year is a leap year.
gregorian_calendar::is_leap_year(2000) --> true

top
Class day_clock
Class day_clock
top
Posix Time
Posix Time
Posix Time System
Posix Time System
Introduction
-- Usage Examples
Introduction
Introduction
Defines a non-adjusted time system with nano-second/micro-second resolution and stable calculation properties. The nano-second resolution option uses 96 bits of underlying storage for each ptime while the micro-second resolution uses 64 bits per ptime (see Build Options for details). This time system uses the Gregorian calendar to implement the date portion of the time representation.
Usage Examples
Usage Examples

Example
Description
Time Math
A few simple calculations using ptime and time_durations.
Print Hours
Retrieve time from clock, use a time_iterator.
Local to UTC Conversion
Demonstrates a couple different ways to convert a local to UTC time including daylight savings rules.
Time Periods
Some simple examples of intersection and display of time periods.

Ptime Class
Introduction
-- Header -- Construction -- Construct from String -- Construct from Clock -- Construct using Conversion functions -- Accessors -- Conversion To String -- Operators Introduction Introduction The class boost::posix_time::ptime is the primary interface for time point manipulation. In general, the ptime class is immutable once constructed although it does allow assignment. Class ptime is dependent on gregorian::date for the interface to the date portion of a time point. Other techniques for creating times include time iterators. Header Header #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o or #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
ptime(date,time_duration)
Construct from a date and offset
ptime t1(date(2002,Jan,10), time_duration(1,2,3)); ptime t2(date(2002,Jan,10), hours(1)+nanosec(5));
ptime(ptime)
Copy constructor
ptime t3(t1)
ptime(special_values sv)
Constructor for infinities, not-a-date-time, max_date_time, and min_date_time
ptime d1(neg_infin); ptime d2(pos_infin); ptime d3(not_a_date_time); ptime d4(max_date_time); ptime d5(min_date_time);
ptime;
Default constructor. Creates a ptime object initialized to not_a_date_time. NOTE: this constructor can be disabled by defining DATE_TIME_NO_DEFAULT_CONSTRUCTOR (see compiler_config.hpp)
ptime p; // p => not_a_date_time

Construct from String
Construct from String

Syntax
Description
Example
ptime time_from_string(const std::string&)
From delimited string.
std::string ts("2002-01-20 23:59:59.000"); ptime t(time_from_string(ts))
ptime from_iso_string(const std::string&)
From non delimited iso form string.
std::string ts("20020131T235959"); ptime t(from_iso_string(ts))

Construct from Clock
Construct from Clock

Syntax
Description
Example
static ptime second_clock::local_time();
Get the local time, second level resolution, based on the time zone settings of the computer.
ptime t(second_clock::local_time())
static ptime second_clock::universal_time()
Get the UTC time.
ptime t(second_clock::universal_day())
static ptime microsec_clock::local_time()
Get the local time using a subsecond resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the acheived resolution.
ptime t(microsec_clock::local_time())

Construct using Conversion Functions
Construct using Conversion Functions

Syntax
Description
Example
ptime from_time_t(time_t t);
Converts a time_t into a ptime.
ptime t = from_time_t(tt);
ptime from_ftime<ptime>(FILETIME ft);
Creates a ptime object from a FILETIME structure.
ptime t = from_ftime<ptime>(ft);

Accessors
Accessors

Syntax
Description
Example
date date() const
Get the date part of a time.
date d(2002,Jan,10); ptime t(d, hour(1)); t.date() --> 2002-Jan-10;
time_duration time_of_day() const
Get the time offset in the day.
date d(2002,Jan,10); ptime t(d, hour(1)); t.time_of_day() --> 01:00:00;

Conversion to String
Conversion to String

Syntax
Description
Example
std::string to_simple_string(ptime)
To YYYY-mmm-DD HH:MM:SS.fffffffff string where mmm 3 char month name. Fractional seconds only included if non-zero.
2002-Jan-01 10:00:01.123456789
std::string to_iso_string(ptime)
Convert to form YYYYMMDDTHHMMSS,fffffffff where T is the date-time separator
20020131T100001,123456789
std::string to_iso_extended_string(ptime)
Convert to form YYYY-MM-DDTHH:MM:SS,fffffffff where T is the date-time separator
2002-01-31T10:00:01,123456789

Operators
Operators

Syntax
Description
Example
operator==, operator!=, operator>, operator< operator>=, operator<=
A full complement of comparison operators
t1 == t2, etc
ptime operator+(date_duration) const
Return a ptime adding a day offset
date d(2002,Jan,1); ptime t(d,minutes(5)); date_duration dd(1); ptime t2 = t + dd;
ptime operator-(date_duration) const
Return a ptime subtracting a day offset
date d(2002,Jan,1); ptime t(d,minutes(5)); date_duration dd(1); ptime t2 = t - dd;
ptime operator+(time_duration) const
Return a ptime adding a time duration
date d(2002,Jan,1); ptime t(d,minutes(5)); ptime t2 = t + hours(1) + minutes(2);
ptime operator-(time_duration) const
Return a ptime subtracting a time duration
date d(2002,Jan,1); ptime t(d,minutes(5)); ptime t2 = t - minutes(2);
time_duration operator-(ptime) const
Take the difference between two times.
date d(2002,Jan,1); ptime t1(d,minutes(5)); ptime t2(d,seconds(5)); time_duration t3 = t2 - t1;//negative result

top
Time Duration
Introduction
-- Header -- Construction -- Count Based Construction -- Construct from String -- Accessors -- Conversion To String -- Operators Introduction Introduction The class boost::posix_time::time_duration the base type responsible for representing a length of time. A duration can be either positive or negative. The general time_duration class provides a constructor that takes a count of the number of hours, minutes, seconds, and fractional seconds count as shown in the code fragment below. The resolution of the time_duration is configureable at compile time. See Build-Compiler Information for more information. using namespace boost::posix_time; time_duration td(1,2,3,4); //01:02:03.000000004 when resolution is nano seconds time_duration td(1,2,3,4); //01:02:03.000004 when resolution is micro seconds Several small helper classes that derive from a base time_duration, as shown below, to adjust for different resolutions. These classes can shorten code and make the intent clearer. As an example: using namespace boost::posix_time; time_duration td = hours(1) + seconds(10); //01:00:01 td = hours(1) + nanosec(5); //01:00:00.000000005 Note that the existence of the higher resolution classes (eg: nanosec) depends on the installation of the library. See Build-Compiler Information for more information. Header Header #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o or #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
time_duration(hours,minutes,seconds,fractional_seconds)
Construct ad duration from the counts
time_duration td(1,2,3,9); //1 hr 2 min 3 sec 9 nanoseconds

Count Based Construction
Count Based Construction

Syntax
Description
Example
hours(long)
Number of hours
time_duration td = hours(3);
minutes(long)
Number of minutes
time_duration td = minutes(3);
seconds(long)
Number of seconds
time_duration td = seconds(3);
millisec(long)
Number of milliseconds.
time_duration td = millisec(3);
microsec(long)
Number of microseconds.
time_duration td = microsec(3);
nanosec(long)
Number of nanoseconds.
time_duration td = nanosec(3);

Construct from String
Construct from String

Syntax
Description
Example
time_duration duration_from_string(const std::string&)
From delimited string.
std::string ts("23:59:59.000"); time_duration td(duration_from_string(ts))

Accessors
Accessors

Syntax
Description
Example
long hours() const
Get the number of normalized hours.
time_duration td(1,2,3); td.hours() --> 1
long minutes() const
Get the number of minutes normalized (0..59).
time_duration td(1,2,3); td.minutes() --> 2
long seconds() const
Get the normalized number of second (0..59).
time_duration td(1,2,3); td.seconds() --> 3
long total_seconds() const
Get the total number of seconds truncating any fractional seconds.
time_duration td(1,2,3,10); td.total_seconds() --> (1*3600) + (2*60) + 3 == 3723
long fractional_seconds() const
Get the number of fractional seconds.
time_duration td(1,2,3, 1000); td.fractional_seconds() --> 1000
bool is_negative() const
True if duration is negative.
time_duration td(-1,0,0); td.is_negative() --> true
time_duration invert_sign() const
Generate a new duration with the sign inverted/
time_duration td(-1,0,0); td.invert_sign() --> 01:00:00
static boost::date_time::time_resolutions resolution()
Describes the resolution capability of the time_duration class. time_resolutions is an enum of resolution possibilities ranging from seconds to nanoseconds.
time_duration::resolution() --> nano
static time_duration::num_fractional_digits()
Returns an unsigned short holding the number of fractional digits the time resolution has.
time_duration::num_fractional_digits(); // 9 for nano, 6 for micro, etc.
boost::int64_t ticks()
Return the raw count of the duration type.
time_duration td(0,0,0, 1000); td.ticks() --> 1000
static time_duration unit()
Return smallest possible unit of duration type (1 nanosecond).
time_duration::unit() --> time_duration(0,0,0,1)

Conversion To String
Conversion To String

Syntax
Description
Example
std::string to_simple_string(time_duration)
To HH:MM:SS.fffffffff were fff is fractional seconds that are only included if non-zero.
10:00:01.123456789
std::string to_iso_string(time_duration)
Convert to form HHMMSS,fffffffff.
100001,123456789

Operators
Operators

Syntax
Description
Example
operator==, operator!=, operator>, operator< operator>=, operator<=
A full complement of comparison operators
dd1 == dd2, etc
time_duration operator+(time_duration) const
Add durations.
time_duration td1(hours(1)+minutes(2)); time_duration td2(seconds(10)); time_duration td3 = td1 + td2;
time_duration operator-(time_duration) const
Subtract durations.
time_duration td1(hours(1)+nanosec(2)); time_duration td2 = td1 - minutes(1);
time_duration operator/(int) const
Divide the length of a duration by an integer value. Discards any remainder.
hours(3)/2 == time_duration(1,30,0); nanosec(3)/2 == nanosec(1)
time_duration operator*(int) const
Multiply the length of a duration by an integer value.
hours(3)*2 == hours(6);

top
Time Period
Introduction
-- Header -- Construction -- Accessors -- Conversion To String -- Operators Introduction Introduction The class boost::posix_time::time_period provides direct representation for ranges between two times. Periods provide the ability to simplify some types of calculations by simplifying the conditional logic of the program. The time periods example provides an example of using time periods. Header Header #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o or #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types Construction Construction

Syntax
Description
Example
time_period(ptime begin, ptime end)
Create a period as [begin, end). If last is <= begin then the period will be defined as null.
date d(2002,Jan,01); ptime t(d, seconds(10)); //10 sec after midnight time_period tp(t, hours(3));
time_period(ptime start, time_duration len)
Create a period as [begin, begin+len). If len is <= zero then the period will be defined as null.
date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2);
time_period(time_period rhs)
Copy constructor
time_period tp1(tp)

Accessors
Accessors

Syntax
Description
Example
ptime begin() const
Return first time of period.
date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.begin() --> 2002-Jan-01 00:00:10
ptime last() const
Return last time in the period
date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.last() --> 2002-Jan-01 09:59:59.999999999
ptime end() const
Return one past the last in period
date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight time_period tp(t1, t2); tp.last() --> 2002-Jan-01 10:00:00
time_duration length() const
Return the length of the time period.
date d(2002,Jan,01); ptime t1(d); //midnight time_period tp(t1, hours(1)); tp.length() --> 1 hour
bool is_null() const
True if period is not well formed. eg: start less than end
bool contains(ptime) const
True if ptime is within the period
date d(2002,Jan,01); ptime t1(d, seconds(10)); //10 sec after midnight ptime t2(d, hours(10)); //10 hours after midnight ptime t3(d, hours(2)); //2 hours after midnight time_period tp(t1, t2); tp.contains(t3) --> true
bool contains(time_period) const
True if period is within the period
time_period tp1(ptime(d,hours(1)), ptime(d,hours(12))); time_period tp2(ptime(d,hours(2)), ptime(d,hours(4))); tp1.contains(tp2) --> true tp2.contains(tp1) --> false
bool intersects(time_period) const
True if periods overlap
time_period tp1(ptime(d,hours(1)), ptime(d,hours(12))); time_period tp2(ptime(d,hours(2)), ptime(d,hours(4))); tp2.intersects(tp1) --> true
time_period intersection(time_period) const
Calculate the intersection of 2 periods. Null if no intersection.
time_period merge(time_period) const
Returns union of two periods. Null if no intersection.
time_period span(time_period) const
Combines two periods and any gap between them such that start = min(p1.start, p2.start) and end = max(p1.end , p2.end).
time_period shift(date_duration)
Add duration to both start and end.

Conversion To String
Conversion To String

Syntax
Description
Example
std::string to_simple_string(time_period dp)
To [YYYY-mmm-DD hh:mm:ss.fffffffff/YYYY-mmm-DD hh:mm:ss.fffffffff] string where mmm is 3 char month name.
[2002-Jan-01 01:25:10.000000001/2002-Jan-31 01:25:10.123456789]

Operators
Operators

Syntax
Description
Example
operator<<
Output streaming operator for time duration. Uses facet to output [date time_of_day/date time_of_day]. The default is format is [YYYY-mmm-DD hh:mm:ss.fffffffff/YYYY-mmm-DD hh:mm:ss.fffffffff] string where mmm is 3 char month name.
[2002-Jan-01 01:25:10.000000001/2002-Jan-31 01:25:10.123456789]
operator==, operator!=
Equality operators. Periods are equal if p1.begin == p2.begin && p1.last == p2.last
if (tp1 == tp2) {...
operator<
Ordering with no overlap. True if tp1.end() less than tp2.begin()
if (tp1 < tp2) {...
operator>
Ordering with no overlap. True if tp1.begin() greater than tp2.end()
if (tp1 > tp2) {... etc
operator<=, operator>=
Defined in terms of the other operators.

top
Time Iterators
Introduction
-- Header -- Overview -- Operators Introduction Introduction Time iterators provide a mechanism for iteration through times. Time iterators are similar to Bidirectional Iterators. However, time_iterators are different than standard iterators in that there is no underlying sequence, just a calculation function. In addition, time_iterators are directly comparable against instances of class ptime. Thus a second iterator for the end point of the iteration is not required, but rather a point in time can be used directly. For example, the following code iterates using a 15 minute iteration interval. The print hours example also illustrates the use of the time_iterator. #include "boost/date_time/posix_time/posix_time.hpp" #include <iostream> int main() { using namespace boost::gregorian; using namespace boost::posix_time; date d(2000,Jan,20); ptime start(d); ptime end = start + hours(1); time_iterator titr(start,minutes(15)); //increment by 15 minutes //produces 00:00:00, 00:15:00, 00:30:00, 00:45:00 while (titr < end) { std::cout << to_simple_string(*titr) << std::endl; ++titr; } std::cout << "Now backward" << std::endl; //produces 01:00:00, 00:45:00, 00:30:00, 00:15:00 while (titr > start) { std::cout << to_simple_string(*titr) << std::endl; --titr; } } Header Header #include "boost/date_time/posix_time/posix_time.hpp" //include all types plus i/o or #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types Overview Overview

Class
Construction Parameters
Description
time_iterator
ptime start_time, time_duration increment
Iterate incrementing by the specified duration.

Operators
Operators

Syntax
Description
Example
operator==(const ptime& rhs), operator!=(const ptime& rhs), operator>, operator< operator>=, operator<=
A full complement of comparison operators
date d(2002,Jan,1); ptime start_time(d, hours(1)); //increment by 10 minutes time_iterator titr(start_time, minutes(10)); ptime end_time = start_time + hours(2); if (titr == end_time) // false if (titr != end_time) // true if (titr >= end_time) // false if (titr <= end_time) // true
prefix increment
Increment the iterator by the specified duration.
//increment by 10 milli seconds time_iterator titr(start_time, milliseconds(10)); ++titr; // == start_time + 10 milliseconds
prefix decrement
Decrement the iterator by the specified time duration.
Example time_iterator titr(start_time, time_duration(1,2,3)); --titr; // == start_time - 1 hour, 2 minutes, and 3 seconds

top
Local Time Adjustment
Introduction
-- Header -- Overview Introduction Introduction A frequent problem in time representation is the conversion between various local time systems. In general this is accomplished by using a reference time system. The reference time system is typically UTC. Since the posix_time system does no internal time adjustment it can be used to represent both local times and UTC times. However, the user is currently left to handle conversions and time zone knowledge explicitly. The library offers two different ways to perform UTC to local conversions. The first is using the time zone settings of the computer. This is a useful solution for converting a UTC time for a user machine. This approach depends on the ctime API and will provide incorrect results if the environment is set incorrectly. The other approach allows conversion from any zone to UTC and back independent of the settings of the time zone settings of the computer. The local utc conversion example demonstrates both of these techniques. Header Header #include "boost/date_time/gregorian/gregorian.hpp" //include all types plus i/o or #include "boost/date_time/gregorian/gregorian_types.hpp" //no i/o just types Overview Overview

Class
Description
Example
date_time::c_local_adjustor<ptime>::utc_to_local(ptime)
Calculate local machine time from a UTC time based on time zone settings and the C API.
typedef boost::date_time::c_local_adjustor<ptime> local_adj; ptime t10(date(2002,Jan,1), hours(7)); ptime t11 = local_adj::utc_to_local(t10);
date_time::local_adjustor<ptime, utc_offset, dst_rules>::utc_to_local(ptime)
Calculate local machine time from a UTC time based daylight savings rules and utc offset
example
date_time::local_adjustor<ptime, utc_offset, dst_rules>::local_to_utc(ptime)
Calculate UTC time based on daylight savings rules and utc offset.
example

top
Details
Details
Calculations
Timepoints
-- Durations -- Intervals (Periods) -- Special Value Handling
Timepoints
Timepoints
This section describes some of basic arithmetic rules that can be performed with timepoints. In general, Timepoints support basic arithmetic in conjunction with Durations as follows: Timepoint + Duration --> Timepoint Timepoint - Duration --> Timepoint Timepoint - Timepoint --> Duration Unlike regular numeric types, the following operations are undefined: Duration + Timepoint --> Undefined Duration - Timepoint --> Undefined Timepoint + Timepoint --> Undefined
Durations
Durations
Durations represent a length of time and can have positive and negative values. It is frequently useful to be able to perform calculations with other durations and with simple integral values. The following describes these calculations: Duration + Duration --> Duration Duration - Duration --> Duration Duration * Integer --> Duration Integer * Duration --> Duration Duration / Integer --> Duration (Integer Division rules)
Intervals (Periods)
Intervals (Periods)
Interval logic is extremely useful for simplifying many 'calculations' for dates and times. The following describes the operations provided by periods which are based on half-open range. The following operations calculate new time periods based on two input time periods: Timeperiod intersection Timeperiod --> Timeperiod (null interval if no intersection) Timeperiod merge Timeperiod --> Timeperiod (null interval if no intersection) Timeperiod shift Duration --> Timeperiod (shift start and end by duration amount) In addition, periods support various queries that calculate boolean results. The first set is caluculations with other time periods: Timeperiod == Timeperiod --> bool Timeperiod < Timeperiod --> bool (true if lhs.last <= rhs.begin) Timeperiod intersects Timeperiod --> bool Timeperiod contains Timeperiod --> bool Timeperiod is_adjacent Timeperiod --> bool The following calculations are performed versus the Timepoint. Timeperiod contains Timepoint --> bool Timeperiod is_before Timepoint --> bool Timeperiod is_after Timepoint --> bool
Special Value Handling
Special Value Handling
For many temporal problems it is useful for Duration and Timepoint types to support special values such as Not A Date Time (NADT) and infinity. In general special values such as Not A Date Time (NADT) and infinity should follow rules like floating point values. Note that it should be possible to configure NADT based systems to throw an exception instead of result in NADT. Timepoint(NADT) + Duration --> Timepoint(NADT) Timepoint(∞) + Duration --> Timepoint(∞) Timepoint + Duration(∞) --> Timepoint(∞) Timepoint - Duration(∞) --> Timepoint(-∞) When performing operations on both positive and negative infinities, the library will produce results consistent with the following. Timepoint(+∞) + Duration(-∞) --> NADT Duration(+∞) + Duration(-∞) --> NADT Duration(±∞) * Zero --> NADT Duration(∞) * Integer(Not Zero) --> Duration(∞) Duration(+∞) * -Integer --> Duration(-∞) Duration(∞) / Integer --> Duration(∞)
Design Goals

Category
Description
Functions
Interfaces
Provide concrete classes for manipulation of dates and times
•
date, time, date_duration, time_duration, date_period, time_period, etc
•
support for infinity - positive infinity, negative infinity
•
iterators over time and date ranges
•
allow date and time implementations to be separate as much as possible
Calculation
Provide a basis for performing efficient time calculations
•
days between dates
•
durations of times
•
durations of dates and times together
Representation Flexibility
Provide the maximum possible reusability and flexibility
•
traits based customization of internal representations for size versus resolution control
•
Allowing the use of different epochs and resolution (eg: seconds versus microseconds, dates starting at the year 2000 versus dates starting in 1700)
•
Options for configuring unique calendar representations (Gregorian + others)
•
the use of Julian Day number and the conversion between this and the Gregorian/Julian calendar date
•
Allow for flexible adjustments including leap seconds
Date Calculations
Provide tools for date calculations
•
provide basis for calculation of complex event specs like holidays
•
calendar to calendar conversions
•
provide for ability to extend to new calendar systems
Time Calculations
Provide concrete classes for manipulation of time
•
provide the ability to handle cross time-zone issues
•
provide adjustments for daylight savings time (summer time)
Clock Interfaces
Provide classes for retrieving time current time
•
access to a network / high resolution time sources
•
retrieving the current date time information to populate classes
I/O Interfaces
Provide input and output for time including
•
multi-lingual support
•
provide ISO8601 compliant time facet
•
use I/O facets for different local behavior

Tradeoffs: Stability, Predictability, and Approximations
Unavoidable Trade-offs
Unavoidable Trade-offs
The library does its best to provide everything a user could want, but there are certain inherent constraints that limit what any temporal library can do. Specifically, a user must choose which two of the following three capabilities are desired in any particular application: •exact agreement with wall-clock time•accurate math, e.g. duration calculations•ability to handle timepoints in the future Some libraries may implicitly promise to deliver all three, but if you actually put them to the test, only two can be true at once. This limitation is not a deficiency in the design or implementation of any particular library; rather it is a consequence of the way different time systems are defined by international standards. Let's look at each of the three cases:
If you want exact agreement with wall-clock time, you must use either UTC or local time. If you compute a duration by subtracting one UTC time from another and you want an answer accurate to the second, the two times must not be too far in the future because leap seconds affect the count but are only determined about 6 months in advance. With local times a future duration calculation could be off by an entire hour, since legislatures can and do change DST rules at will.
If you want to handle wall-clock times in the future, you won't be able (in the general case) to calculate exact durations, for the same reasons described above.
If you want accurate calculations with future times, you will have to use TAI or an equivalent, but the mapping from TAI to UTC or local time depends on leap seconds, so you will not have exact agreement with wall-clock time.
Stability, Predictability, and Approximations
Stability, Predictability, and Approximations
Here is some underlying theory that helps to explain what's going on. Remember that a temporal type, like any abstract data type (ADT), is a set of values together with operations on those values.
Stability
Stability
The representation of a type is stable if the bit pattern associated with a given value does not change over time. A type with an unstable representation is unlikely to be of much use to anyone, so we will insist that any temporal library use only stable representations.
An operation on a type is stable if the result of applying the operation to a particular operand(s) does not change over time.
Predictability
Predictability
Sets are most often classified into two categories: well-defined and ill-defined. Since a type is a set, we can extend these definitions to cover types. For any type T, there must be a predicate is_member( x ) which determines whether a value x is a member of type T. This predicate must return true, false, or dont_know.
If for all x, is_member( x ) returns either true or false, we say the set T is well-defined.
If for any x, is_member( x ) returns dont_know, we say the set T is ill-defined.
Those are the rules normally used in math. However, because of the special characteristics of temporal types, it is useful to refine this view and create a third category as follows:
For any temporal type T, there must be a predicate is_member( x, t ) which determines whether a value x is a member of T. The parameter t represents the time when the predicate is evaluated. For each xi, there must be a time ti and a value v such that: •v = true or v = false, and•for all t < ti, is_member( xi, t ) returns dont_know, and•for all t >= ti, is_member( xi, t ) returns v. ti is thus the time when we "find out" whether xi is a member of T. Now we can define three categories of temporal types:
If for all xi, ti = negative infinity, we say the type T is predictable.
If for some xi, ti = positive infinity, we say the type T is ill-formed.
Otherwise we say the type T is unpredictable (this implies that for some xi, ti is finite).
Ill-formed sets are not of much practical use, so we will not discuss them further. In plain english the above simply says that all the values of a predictable type are known ahead of time, but some values of an unpredictable type are not known until some particular time.
Stability of Operations
Stability of Operations
Predictable types have a couple of important properties: •there is an order-preserving mapping from their elements onto a set of consecutive integers, and•duration operations on their values are stable
The practical effect of this is that duration calculations can be implemented with simple integer subtraction. Examples of predictable types are TAI timepoints and Gregorian dates.
Unpredictable types have exactly the opposite properties: •there is no order-preserving mapping from their elements onto a set of consecutive integers, and•duration operations on their values are not stable.
Examples of unpredictable types are UTC timepoints and Local Time timepoints.
We can refine this a little by saying that a range within an unpredicatable type can be predictable, and operations performed entirely on values within that range will be stable. For example, the range of UTC timepoints from 1970-01-01 through the present is predictable, so calculations of durations within that range will be stable.
Approximations
Approximations
These limitations are problematical, because important temporal types like UTC and Local Time are in fact unpredictable, and therefore operations on them are sometimes unstable. Yet as a practical matter we often want to perform this kind of operation, such as computing the duration between two timepoints in the future that are specified in Local Time.
The best the library can do is to provide an approximation, which is generally possible and for most purposes will be good enough. Of course the documentation must specify when an answer will be approximate (and thus unstable) and how big the error may be. In many respects calculating with unpredictable sets is analogous to the use of floating point numbers, for which results are expected to only be approximately correct. Calculating with predictable sets would then be analogous to the user of integers, where results are expected to be exact.
For situations where exact answers are required or instability cannot be tolerated, the user must be able to specify this, and then the library should throw an exception if the user requests a computation for which an exact, stable answer is not possible.
Serialization
The boost::date_time library is compatible with the boost::serialization library's text and xml archives. The list of classes that are serializable are:
boost::gregorian
boost::gregorian

date
date_duration
date_period
partial_date
nth_day_of_week_in_month
first_day_of_week_in_month
last_day_of_week_in_month
first_day_of_week_before
first_day_of_week_after
greg_month
greg_day
greg_weekday

boost::posix_time
boost::posix_time

ptime
time_duration
time_period

No extra steps are required to build the date_time library for serialization use.
Example text_archive usage: using namespace boost::posix_time; using namespace boost::gregorian; ptime pt(date(2002, Feb, 14)), hours(10)), pt2(not_a_date_time); std::ofstream ofs("tmp_file"); archive::test_oarchive oa(ofs); oa << pt; // NOTE: no macro ofs.close(); std::ifstream ifs("tmp_file"); archive::text_iarchive ia(ifs); ia >> pt2; // NOTE: no macro ifs.close(); pt == pt2; // true
Example xml_archive usage: using namespace boost::gregorian; date d(2002, Feb, 14), d2(not_a_date_time); std::ofstream ofs("tmp_file"); archive::xml_oarchive oa(ofs); oa << BOOST_SERIALIZATION_NVP(d); // macro required for xml_archive ofs.close(); std::ifstream ifs("tmp_file"); archive::xml_iarchive ia(ifs); ia >> BOOST_SERIALIZATION_NVP(d2); // macro required for xml_archive ifs.close(); d == d2; // true
To use the date_time serialization code, the proper header files must be explicitly included. The header files are: boost/date_time/gregorian/greg_serialize.hpp and boost/date_time/posix_time/time_serialize.hpp
Terminology
The following are a number of terms relevant to the date-time domain.
A taxonomy of temporal types: •Timepoint -- Specifier for a location in the time continuum. Similar to a number on a ruler.•Timelength -- A duration of time unattached to any point on the time continuum.•Timeinterval -- A duration of time attached to a specific point in the time continuum.
And some other terms: •Accuracy -- A measure of error, the difference between the reading of a clock and the true time.•Calendar System -- A system for labeling time points with day level resolution.•Clock Device -- A software component (tied to some hardware) that provides the current date or time with respect to a calendar or clock system.•Precision -- A measure of repeatability of a clock.•Resolution -- A specification of the smallest representable duration (eg: 1 second, 1 century) for a clock/calendar system or temporal type.•Stability -- The property of a class which says that the underlying representation (implementation) associated with a particular (abstract) value will never change.•Time System -- A system for labeling time points with higher resolution than day-level.
Some standard date-time terminology: •Epoch -- Starting time point of a calendar or clock system.•DST -- Daylight savings time - a local time adjustment made in some regions during the summer to shift the clock time of the daylight hours•Time zone -- A region of the earth that provides for a 'local time' defined by DST rules and UT offset.•UTC Time -- Coordinated Universal Time - Civil time system as measured at longitude zero. Kept adjusted to earth rotation by use of leap seconds. Also known as Zulu Time. Replaced the similar system known as Greenwich Mean Time. For more see http://aa.usno.navy.mil/faq/docs/UT.html•TAI Time -- A high-accuracy monotonic (need better term) time system measured to .1 microsecond resolution by atomic clocks around the world. Not adjusted to earth rotation. For more see http://www.bipm.fr/enus/5_Scientific/c_time/time_server.html
Some more experimental ones: •Local Time -- A time measured in a specific location of the universe.•Time Label -- A tuple that either completely or partially specifies a specific date-time with respect to a calendar or clock system. This is the year-month-day representation.•Adjusting Time Length -- A duration that represents varying physical durations depending on the moment in time. For example, a 1 month duration is typically not a fixed number of days and it depends on the date it is measured from to determine the actual length.
These are design sorts of terms: •Generation function -- A function that generates a specific set of time points, lengths, or intervals based on one or more parameters.
References
•
Date References
•
Time References
•
Other C/C++ Libraries
•
JAVA Date-Time Libraries
•
Scripting Language Libraries
•
Related Commercial and Fanciful Pages
•
Resolution, Precision, and Accuracy
Date Calendar References
Date Calendar References
•
ISO 8601 date time standard -- Summary by Markus Kuhn
•
Calendrical Calculations
book by Reingold & Dershowitz
•
Calendar FAQ by Claus Tøndering
•
Calendar zone http://www.calendarzone.com
•
XML schema for date time
•
Will Linden's Calendar Links
•
XMAS calendar melt
Time
Time
•
Martin Folwer on time patterns •Recurring Events for Calendars•Patterns for things that Change with time
•
US National Institute of Standards and Technology Time Exhibits
•
Network Time Protocol at NTP.org
•
US Navy Systems of Time
•
International Atomic Time
•
Date-Time type PostgreSQL
User Guide
Other C/C++ Libraries
Other C/C++ Libraries
•
ctime C
Standard library reference at cplusplus.com
•
XTime C extension
proposal
•
Another C library extension proposal
by David Tribble
•
libTAI
is a C based time library
•
Time Zone Database
C library for managing timezones/places
•
International Components for Unicode by IBM (open source) •Calendar Class•Date Time Services•Time Zone Class•Date-Time Formatting
•
Julian Library in C by Mark Showalter -- NASA
JAVA Date & Time Library Quick Reference
JAVA Date & Time Library Quick Reference
•
Calendar class
•
Gregorian calendar
•
Date class
•
sql.time class
•
Date format symbols
•
Date format
•
Simple Date Format
•
Simple Time Zone
Scripting Language Libraries
Scripting Language Libraries
•
A python date library MX Date Time
•
Perl date-time •Date-Time packages at CPAN•Date::Calc at CPAN•Date::Convert calendar conversions at CPAN
•
A PHP library Vlib Date Library
Related Commercial and Fanciful Pages
Related Commercial and Fanciful Pages
•
Leapsecond.com time
page
•
World Time Server / TZ database
•
10000 year clock
at Long Now Foundation
•
Timezones for PCs
Resolution, Precision, and Accuracy
Resolution, Precision, and Accuracy
•
Definitions with pictures from Agilent Technologies
•
Another set of pictures from Team Labs
•
Definitions from Southampton Institute
•
Definitions from Newport Corporation in the context of instrumentation
Build-Compiler Information
Overview
-- Compilation Options -- Compiler/Portability Notes -- Directory Structure -- Required Boost Libraries
Overview
Overview
The library has several functions that require the creation of a library file. The Jamfile in the build directory will produce a "static" library (libboost_date_time) and a "dynamic/shared" library (boost_date_time) that contains these functions.
Compilation Options
Compilation Options
By default the posix_time system uses a 64 bit integer and a 32 bit integer internally to provide nano-second level resolutions. As an alternative, a single 64 bit integer can be used to provide a microsecond level resolution. This alternative implementation may provide better performance and more compact memory usage for many applications that do not require nano-second resolutions.
To use the alternate resolution (64 bit microsecond) the variable BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG must be defined in the library users project files (ie Makefile, Jamfile, etc). This macro is not used by the Gregorian system and therefore has no effect when building the library.
Compiler/Portability Notes
Compiler/Portability Notes
The Boost Date-Time library has been built and tested with many compilers. However, some compilers and standard libraries have issues. While some of these issues can be worked around, others are difficult to work around. The following compilers fully support all aspects of the library: •GCC 3.2-7 on Linux•GCC 2.95.3 with STLport-4.5.3 on Linux•GCC 3.1 (cygwin)•MSVC 7.1
In particular, a lack of support for standard locales limits the ability of the library to support iostream based input output. For these compilers a set of more limited string based input-output is provided. The compilers/standard libraries with this limitation include: •GCC 2.9x on Linux•Borland 5.1.1 and 5.6•MSVC 6 SP5
Other compilers such as Comeau and Metroworks have been tested successfully with earlier versions of the library.
Directory Structure
Directory Structure
The directory tree has the following structure: /boost/date_time -- common headers and template code /boost/date_time/gregoran -- Gregorian calendar system header files /boost/date_time/posix_time -- posix time system headers /libs/date_time/build -- build files and output directory /libs/date_time/test -- test battery for generic code /libs/date_time/test/gregorian -- test battery for the Gregorian system /libs/date_time/test/posix_time -- test battery for the posix_time system /libs/date_time/examples/posix_time -- time example programs /libs/date_time/examples/gregorian -- nifty example programs /libs/date_time/src/gregorian -- cpp files for libboost_date_time /libs/date_time/src/posix_time -- empty (one file, but no source code...)
Required Boost Libraries
Required Boost Libraries
The library depends on •boost.tokenizer•boost.integer(cstdint)•boost.operators•boost::lexical_cast so at least these libraries need to be installed.
Tests
The library provides a large number of tests in the libs/date_time/test libs/date_time/test/gregorian libs/date_time/test/posix_time directories. Building and executing these tests assures that the installation is correct and that the library is functioning correctly. In addition, these tests facilitate the porting to new compilers. Finally, the tests provide examples of many functions not explicitly described in the usage examples.
Change History
Changes from Boost 1.31 to 1.32 (date_time 1.02 to 1.03)
Changes from Boost 1.31 to 1.32 (date_time 1.02 to 1.03)

Type
Description
Bug Fix
Snap to end of month behavior corrected for year_functor. Previously, starting from 2000-Feb-28 (leap year and not end of month) and iterating through the next leap year would result in 2004-Feb-29 instead of 2004-Feb-28. This behavior has been corrected to produce the correct result of 2004-Feb-28. Thanks to Bart Garst for this change.
Feature
Free function for creating a ptime object from a FILETIME struct. This function is only available on platforms that define BOOST_HAS_FTIME.
Feature
Microsecond time clock is now available on most windows compilers as well as Unix.
Feature
Use of the boost::serialization library is now available with most of the date_time classes. Classes capable of serialization are: date_generator classes, date, days, date_period, greg_month, greg_weekday, greg_day, ptime, time_duration, and time_period. Thanks to Bart Garst for this change.
Feature
Functions added to convert date and time classes to wstring. The library now provides to_*_wstring as well as to_*_string functions for: simple, iso, iso_extended, and sql for dates and compilers that support wstrings. Thanks to Bart Garst for this change.
Feature
Period classes now handle zero length and NULL periods correctly. A NULL period is a period with a negative length. Thanks to Frank Wolf and Bart Garst for this change.
Feature
Added end_of_month function to gregorian::date to return the last day of the current month represented by the date. Result is undefined for not_a_date_time or infinities.
Bug Fix
Removed incorrect usage of BOOST_NO_CWCHAR macro throughout library.
Feature
New names added for some date classes. Original names are still valid but may some day be deprecated. Changes are:

date_duration
is now
days
nth_kday_of_month
is now
nth_day_of_the_week_in_month
first_kday_of_month
is now
first_day_of_the_week_in_month
last_kday_of_month
is now
last_day_of_the_week_in_month
first_kday_after
is now
first_day_of_the_week_after
first_kday_before
is now
first_day_of_the_week_before

Feature
Free functions for date generators added. Functions are: days_until_weekday, days_before_weekday, next_weekday, and previous_weekday. days days_until_weekday(date, greg_weekday); days days_before_weekday(date, greg_weekday); date next_weekday(date, greg_weekday); date previous_weekday(date, greg_weekday); Thanks to Bart Garst for this change.
Feature
New experimental duration types added for months, years, and weeks. These classes also provide mathematical operators for use with date and time classes. Be aware that adding of months or years a time or date past the 28th of a month may show non-normal mathematical properties. This is a result of 'end-of-month' snapping used in the calculation. The last example below illustrates the issue.

months m(12); years y(1); m == y; // true days d(7); weeks w(1); d == w; // true ptime t(...); t += months(3); date d(2004,Jan,30); d += months(1); //2004-Feb-29 d -= months(1); //2004-Jan-29
Input streaming is not yet implemented for these types. Thanks to Bart Garst for this change.
Feature
Unifying base class for date_generators brought in to gregorian namespace. See Print Holidays Example.
Feature
Added constructors for date and ptime that allow for default construction (both) and special values construction (ptime, both now support this). Default constructors initialize the objects to not_a_date_time (NADT). ptime p_nadt(not_a_date_time), p_posinf(pos_infin); ptime p; // p == NADT date d; // d == NADT Thanks to Bart Garst for this change.
Feature
Output streaming now supports wide stream output on compiler / standard library combinations that support wide streams. This allows code like: std::wstringstream wss; date d(2003,Aug,21); wss << d; Thanks to Bart Garst for this change.
Feature
Input streaming for date and time types is now supported on both wide and narrow streams: date d(not_a_date_time); std::stringstream ss("2000-FEB-29"); ss >> d; //Feb 29th, 2000 std::wstringstream ws("2000-FEB-29"); ws >> d; //Feb 29th, 2000 Thanks to Bart Garst for this change.
Bug Fix
Fixed bug in duration_from_string() where a string formatted with less than full amount of fractional digits created an incorrect time_duration. With microsecond resolution for time durations the string "1:01:01.010" created a time duration of 01:01:01.000010 instead of 01:01:01.010000
Bug Fix
Fixed the special value constructor for gregorian::date and posix_time::ptime when constructing with min_date_time or max_date_time. The wrong value was constructed for these.

Changes from Boost 1.30 to 1.31 (date_time 1.01 to 1.02)
Changes from Boost 1.30 to 1.31 (date_time 1.01 to 1.02)

Type
Description
Bug Fix
Build configuration updated so dll, statically, and dynamically linkable library files are now produced with MSVC compilers. See Build/Compiler Information for more details.
Bug Fix
Time_duration from_string is now correctly constructed from a negative value. (ie "-0:39:00.000") Code provided by Bart Garst.
Bug Fix
Fixed many MSVC compiler warnings when compiled with warning level 4.
Feature
Added prefix decrement operator (--) for date and time iterators. See Time Iterators and Date Iterators for more details. Code provided by Bart Garst.
Feature
Special_values functionality added for date_duration, time_duration and time classes. Code provided by Bart Garst.
Bug Fix
Fixed time_duration_traits calculation bug which was causing time duration to be limited to 32bit range even when 64 bits were available. Thanks to Joe de Guzman for tracking this down.
Bug Fix
Provided additional operators for duration types (eg: date_duration, time_duration). This includes dividable by integer and fixes to allow +=, -= operators. Thanks to Bart Garst for writing this code. Also, the documentation of Calculations has been improved.
Bug Fix
Added typedefs to boost::gregorian gregorian_types.hpp various date_generator function classes.
Feature
Added from_time_t function to convert time_t to a ptime.
Feature
Added a span function for combining periods. See date period and time period docs.
Feature
Added a function to time_duration to get the total number of seconds in a duration truncating any fractional seconds. In addition, other resolutions were added to allow for easy conversions. For example seconds(1).total_milliseconds() == 1000 seconds(1).total_microseconds() == 1000000 hours(1).total_milliseconds() == 3600*1000 //3600 sec/hour seconds(1).total_nanoseconds() == 1000000000
Feature
Added output streaming operators for the date generator classes - partial_date, first_kday_after, first_kday_before, etc. Thanks to Bart Garst for this work.
Feature
Added unary- operators for durations for reversing the sign of a time duration. For example: time_duration td(5,0,0); //5 hours td = -td; //-5 hours Thanks to Bart Garst for this work.
Feature
Added support for parsing strings with 'month names'. Thus creating a date object from string now accepts multiple formats ("2003-10-31","2003-Oct-31", and "2003-October-31"). Thus, date d = from_simple_string("2003-Feb-27") is now allowed. A bad month name string ( from_simple_string("2003-SomeBogusMonthName-27")) will cause a bad_month exception. On most compilers the string compare is case insensitive. Thanks to Bart Garst for this work.
Feature
In addition to support for month names or numbers, functions have been added to create date objects from multi-ordered date strings. Ex: "January-21-2002", "2002-Jan-21", and "21-Jan-2003". See Date Class for more details.
Bug-Fix
Various documentation fixes. Thanks to Bart Garst for updates.

Changes from Boost 1.29 to 1.30 (date_time 1.00 to 1.01)
Changes from Boost 1.29 to 1.30 (date_time 1.00 to 1.01)
Notice: The interface to the partial_date class (see date_algorithms) was changed. The order of construction parameters was changed which will cause some code to fail execution. This change was made to facilitate more generic local time adjustment code. Thus instead of specifying partial_date pd(Dec,25) the code needs to be changed to partial_date pd(25, Dec);

Type
Description
Bug Fix
Added new experimental feature for Daylight Savings Time calculations. This allows traits based specification of dst rules.
Feature
Added new interfaces to calculate julian day and modified julian day to the gregorian date class. See boost::gregorian::date.
Feature
Add new interface to calculate iso 8601 week number for a date. See boost::gregorian::date.
Feature
Add an iso 8601 time date-time format (eg: YYYYMMDDTHHHMMSS) parsing function. See Class ptime for more information.
Feature
Added a length function to the period template so that both date_periods and time_periods will now support this function.
Bug Fix
Split Jamfiles so that libs/date_time/build/Jamfile only builds library and /libs/date_time/libs/test/Jamfile which runs tests.
Bug Fix
Fixed many minor documentation issues.
Bug Fix
Removed the DATE_TIME_INLINE macro which was causing link errors. This macro is no longer needed in projects using the library.
Bug Fix
Added missing typedef for year_iterator to gregorian_types.hpp
Bug Fix
Fixed problem with gregorian ostream operators that prevented the use of wide streams.
Bug-Fix
Tighten error handling for dates so that date(2002, 2, 29) will throw a bad_day_of_month exception. Previously the date would be incorrectly constructed. Reported by sourceforge bug: 628054 among others.

Acknowledgements
Many people have contributed to the development of this library. In particular Hugo Duncan and Joel de Guzman for help with porting to various compilers. For initial development of concepts and design Corwin Joy and Michael Kenniston deserve special thanks. Also extra thanks to Michael for writing up the theory and tradeoffs part of the documentation. Dave Zumbro for initial inspiration and sage thoughts. Many thanks to boost reviewers and users including: William Seymour, Kjell Elster, Beman Dawes, Gary Powell, Andrew Maclean, William Kempf, Peter Dimov, Chris Little, David Moore, Darin Adler, Gennadiy Rozental, Joachim Achtzehnter, Paul Bristow, Jan Langer, Mark Rodgers, Glen Knowles, Matthew Denman, and George Heintzelman.
Examples
Examples
General Usage Examples
The following provides some sample usage of dates. See Date Programming for more details.

using namespace boost::gregorian; date weekstart(2002,Feb,1); date weekend = weekstart + week(1); date d2 = d1 + days(5); date today = day_clock::local_day(); if (d2 >= today) {} //date comparison operators

date_period thisWeek(d1,d2); if (thisWeek.contains(today)) {}//do something

//iterate and print the week day_iterator itr(weekstart); while (itr <= weekend) { std::cout << (*itr) << std::endl; ++itr; } //input streaming std::stringstream ss("2004-Jan-1"); ss >> d3;

//localized i/o using facets std::locale global; std::locale german(global, new date_facet(de_short_month_names, de_long_month_names, de_special_value_names, de_long_weekday_names, de_long_weekday_names, '.', boost::date_time::ymd_order_dmy)); std::cout.imbue(global2); date d4(2002, Oct, 1); std::cout << d4; //01.Okt.2002

//date generator functions date d5 = next_weekday(d4, Sunday); //calculate sunday following d4

//define a shorthand for the nth_day_of_the_week_in_month function object typedef nth_day_of_the_week_in_month nth_dow; //US labor day is first Monday in Sept nth_dow labor_day(nth_dow::first,Monday, Sep); date d6 = labor_day.get_date(2004); //calculate a specific date from functor

The following provides some example code using times. See Time Programming for more details.

use namespace boost::posix_time; date d(2002,Feb,1); //an arbitrary date ptime t1(d, hours(5)+nanosec(100)); //date + time of day offset ptime t2 = t1 - minutes(4)+seconds(2); ptime now = second_clock::local_time(); //use the clock date today = now.date(); //Get the date part out of the time date tommorrow = today + date_duration(1); ptime tommorrow_start(tommorrow); //midnight

//input streaming std::stringstream ss("2004-Jan-1 05:21:33.20"); ss >> t2;

//starting at current time iterator adds by one hour time_iterator titr(now,hours(1)); for (; titr < tommorrow_start; ++titr) { std::cout << (*titr) << std::endl; }

top
Dates as Strings
Various parsing and output of strings.

/* The following is a simple example that shows conversion of dates * to and from a std::string. * * Expected output: * 2001-Oct-09 * 2001-10-09 * Tuesday October 9, 2001 * An expected exception is next: * Exception: Month number is out of range 1..12 */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream> #include <string>

int main() {

using namespace boost::gregorian;

try { // The following date is in ISO 8601 extended format (CCYY-MM-DD) std::string s("2001-10-9"); //2001-October-09 date d(from_simple_string(s)); std::cout << to_simple_string(d) << std::endl;

//Read ISO Standard(CCYYMMDD) and output ISO Extended std::string ud("20011009"); //2001-Oct-09 date d1(from_undelimited_string(ud)); std::cout << to_iso_extended_string(d1) << std::endl;

//Output the parts of the date - Tuesday October 9, 2001 date::ymd_type ymd = d1.year_month_day(); greg_weekday wd = d1.day_of_week(); std::cout << wd.as_long_string() << " " << ymd.month.as_long_string() << " " << ymd.day << ", " << ymd.year << std::endl;

//Let's send in month 25 by accident and create an exception std::string bad_date("20012509"); //2001-??-09 std::cout << "An expected exception is next: " << std::endl; date wont_construct(from_undelimited_string(bad_date)); //use wont_construct so compiler doesn't complain, but you wont get here! std::cout << "oh oh, you shouldn't reach this line: " << to_iso_string(wont_construct) << std::endl; } catch(std::exception& e) { std::cout << " Exception: " << e.what() << std::endl; }

return 0; }

top
Days Alive
Calculate the number of days you have been living using durations and dates.

/* Short example that calculates the number of days since user was born. * Demonstrates comparisons of durations, use of the day_clock, * and parsing a date from a string. */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream>

int main() {

using namespace boost::gregorian; std::string s; std::cout << "Enter birth day YYYY-MM-DD (eg: 2002-02-01): "; std::cin >> s; try { date birthday(from_simple_string(s)); date today = day_clock::local_day(); days days_alive = today - birthday; days one_day(1); if (days_alive == one_day) { std::cout << "Born yesterday, very funny" << std::endl; } else if (days_alive < days(0)) { std::cout << "Not born yet, hmm: " << days_alive.days() << " days" <<std::endl; } else { std::cout << "Days alive: " << days_alive.days() << std::endl; }

} catch(...) { std::cout << "Bad date entered: " << s << std::endl; } return 0; }

top
Days Between New Years
Calculate the number of days till new years

/* Provides a simple example of using a date_generator, and simple * mathematical operatorations, to calculate the days since * New Years day of this year, and days until next New Years day. * * Expected results: * Adding together both durations will produce 366 (365 in a leap year). */ #include <iostream> #include "boost/date_time/gregorian/gregorian.hpp"

int main() {

using namespace boost::gregorian;

date today = day_clock::local_day(); partial_date new_years_day(1,Jan); //Subtract two dates to get a duration days days_since_year_start = today - new_years_day.get_date(today.year()); std::cout << "Days since Jan 1: " << days_since_year_start.days() << std::endl;

days days_until_year_start = new_years_day.get_date(today.year()+1) - today; std::cout << "Days until next Jan 1: " << days_until_year_start.days() << std::endl; return 0; };

top
End of the Months
Iterates accross the remaining months in a given year, always landing on the last day of the month.

/* Simple program that uses the gregorian calendar to find the last * day of the month and then display the last day of every month left * in the year. */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream>

int main() { using namespace boost::gregorian;

std::cout << " Enter Year(ex: 2002): "; int year, month; std::cin >> year; std::cout << " Enter Month(1..12): "; std::cin >> month; try { int day = gregorian_calendar::end_of_month_day(year,month); date end_of_month(year,month,day);

//Iterate thru by months -- month_iterator mitr(end_of_month,1); date start_of_next_year(year+1, Jan, 1); //loop thru the days and print each one while (mitr < start_of_next_year){ std::cout << to_simple_string(*mitr) << std::endl; ++mitr; }

} catch(...) { std::cout << "Invalid Date Entered" << std::endl; } return 0;

}

top
Localization Demonstration
The boost::date_time library provides the ability to create customized locale facets. Date ordering, language, seperators, and abbreviations can be customized.

/* The following shows the creation of a facet for the output of * dates in German (please forgive me for any errors in my German -- * I'm not a native speaker). */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream>

/* Define a series of char arrays for short and long name strings to be * associated with date output. */ const char* const de_short_month_names[] = { "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "NAM" }; const char* const de_long_month_names[] = { "Januar", "Februar", "Marz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember", "NichtDerMonat" }; const char* const de_special_value_names[] = { "NichtDatumzeit", "-unbegrenztheit", "+unbegrenztheit" }; const char* const de_long_weekday_names[] = { "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag" }; const char* const de_short_weekday_names[] = { "Son", "Mon", "Die","Mit", "Don", "Fre", "Sam" };

const char* const us_short_month_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "NAD" }; const char* const us_long_month_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "Not-A-Date" }; const char* const us_special_value_names[] = { "Not-A-Date", "-infinity", "+infinity" }; const char* const us_long_weekday_names[] = { "Sunday", "Monday", "Tuesday", "Wenesday", "Thursday", "Friday", "Saturday" }; const char* const us_short_weekday_names[] = { "Sun", "Mon", "Tue","Wed", "Thu", "Fri", "Sat" };

int main() {

#ifndef BOOST_DATE_TIME_NO_LOCALE

using namespace boost::gregorian; typedef boost::date_time::all_date_names_put<greg_facet_config> date_facet;

//create a new local std::locale default_locale; std::locale german_dates1(default_locale, new date_facet(de_short_month_names, de_long_month_names, de_special_value_names, de_short_weekday_names, de_long_weekday_names, '.', boost::date_time::ymd_order_dmy, boost::date_time::month_as_integer));

date d1(2002, Oct, 1); std::cout.imbue(german_dates1); // output the date in German using short month names std::cout << d1 << std::endl; //01.10.2002

std::locale german_dates2(default_locale, new date_facet(de_short_month_names, de_long_month_names, de_special_value_names, de_short_weekday_names, de_long_weekday_names, '.', boost::date_time::ymd_order_dmy, boost::date_time::month_as_long_string));

std::cout.imbue(german_dates2); greg_month m = d1.month(); std::cout << m << std::endl; //Oktober

greg_weekday wd = d1.day_of_week(); std::cout << wd << std::endl; //Dienstag

//Numeric date format with US month/day/year ordering std::locale usa_dates1(default_locale, new date_facet(us_short_month_names, us_long_month_names, us_special_value_names, us_short_weekday_names, us_long_weekday_names, '/', boost::date_time::ymd_order_us, boost::date_time::month_as_integer));

std::cout.imbue(usa_dates1); std::cout << d1 << std::endl; // 10/01/2002 //English names, iso order (year-month-day), '-' separator std::locale usa_dates2(default_locale, new date_facet(us_short_month_names, us_long_month_names, us_special_value_names, us_short_weekday_names, us_long_weekday_names, '-', boost::date_time::ymd_order_iso, boost::date_time::month_as_short_string));

std::cout.imbue(usa_dates2); std::cout << d1 << std::endl; // 2002-Oct-01

#else std::cout << "Sorry, localization is not supported by this compiler/library" << std::endl; #endif return 0;

}

top
Date Period Calculations
Calculates if a date is in an 'irregular' collection of periods using period calculation functions.

/* This example demonstrates a simple use of periods for the calculation of date information.

The example calculates if a given date is a weekend or holiday given an exclusion set. That is, each weekend or holiday is entered into the set as a time interval. Then if a given date is contained within any of the intervals it is considered to be within the exclusion set and hence is a offtime.

Output: Number Excluded Periods: 5 20020202/20020203 20020209/20020210 20020212/20020212 20020216/20020217 In Exclusion Period: 20020216 --> 20020216/20020217 20020223/20020224

*/

#include "boost/date_time/gregorian/gregorian.hpp" #include <set> #include <algorithm> #include <iostream>

typedef std::set<boost::gregorian::date_period> date_period_set;

//Simple population of the exclusion set date_period_set generateExclusion() { using namespace boost::gregorian; date_period periods_array[] = { date_period(date(2002,Feb,2), date(2002,Feb,4)),//weekend of 2nd-3rd date_period(date(2002,Feb,9), date(2002,Feb,11)), date_period(date(2002,Feb,16), date(2002,Feb,18)), date_period(date(2002,Feb,23), date(2002,Feb,25)), date_period(date(2002,Feb,12), date(2002,Feb,13))//a random holiday 2-12 }; const int num_periods = sizeof(periods_array)/sizeof(date_period);

date_period_set ps; //insert the periods in the set std::insert_iterator<date_period_set> itr(ps, ps.begin()); std::copy(periods_array, periods_array+num_periods, itr ); return ps;

}

int main() { using namespace boost::gregorian;

date_period_set ps = generateExclusion(); std::cout << "Number Excluded Periods: " << ps.size() << std::endl;

date d(2002,Feb,16); date_period_set::const_iterator i = ps.begin(); //print the periods, check for containment for (;i != ps.end(); i++) { std::cout << to_iso_string(*i) << std::endl; //if date is in exclusion period then print it if (i->contains(d)) { std::cout << "In Exclusion Period: " << to_iso_string(d) << " --> " << to_iso_string(*i) << std::endl; } }

return 0;

}

top
Print Holidays
This is an example of using functors to define a holiday schedule

/* Generate a set of dates using a collection of date generators * Output looks like: * Enter Year: 2002 * 2002-Jan-01 [Tue] * 2002-Jan-21 [Mon] * 2002-Feb-12 [Tue] * 2002-Jul-04 [Thu] * 2002-Sep-02 [Mon] * 2002-Nov-28 [Thu] * 2002-Dec-25 [Wed] * Number Holidays: 7 */

#include "boost/date_time/gregorian/gregorian.hpp" #include <algorithm> #include <functional> #include <vector> #include <iostream> #include <set>

void print_date(boost::gregorian::date d) { using namespace boost::gregorian; #if defined(BOOST_DATE_TIME_NO_LOCALE) std::cout << to_simple_string(d) << " [" << d.day_of_week() << "]\n"; #else std::cout << d << " [" << d.day_of_week() << "]\n"; #endif }

int main() {

std::cout << "Enter Year: "; int year; std::cin >> year;

using namespace boost::gregorian;

//define a collection of holidays fixed by month and day std::vector<year_based_generator*> holidays; holidays.push_back(new partial_date(1,Jan)); //Western New Year holidays.push_back(new partial_date(4,Jul)); //US Independence Day holidays.push_back(new partial_date(25, Dec));//Christmas day

//define a shorthand for the nth_day_of_the_week_in_month function object typedef nth_day_of_the_week_in_month nth_dow;

//US labor day holidays.push_back(new nth_dow(nth_dow::first, Monday, Sep)); //MLK Day holidays.push_back(new nth_dow(nth_dow::third, Monday, Jan)); //Pres day holidays.push_back(new nth_dow(nth_dow::second, Tuesday, Feb)); //Thanksgiving holidays.push_back(new nth_dow(nth_dow::fourth, Thursday, Nov));

typedef std::set<date> date_set; date_set all_holidays;

for(std::vector<year_based_generator*>::iterator it = holidays.begin(); it != holidays.end(); ++it) { all_holidays.insert((*it)->get_date(year)); }

//print the holidays to the screen std::for_each(all_holidays.begin(), all_holidays.end(), print_date); std::cout << "Number Holidays: " << all_holidays.size() << std::endl;

return 0; }

top
Print Month
Simple utility to print out days of the month with the days of a month. Demontstrates date iteration (date_time::date_itr).

/* This example prints all the dates in a month. It demonstrates * the use of iterators as well as functions of the gregorian_calendar * * Output: * Enter Year: 2002 * Enter Month(1..12): 2 * 2002-Feb-01 [Fri] * 2002-Feb-02 [Sat] * 2002-Feb-03 [Sun] * 2002-Feb-04 [Mon] * 2002-Feb-05 [Tue] * 2002-Feb-06 [Wed] * 2002-Feb-07 [Thu] */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream>

int main() { std::cout << "Enter Year: "; int year, month; std::cin >> year; std::cout << "Enter Month(1..12): "; std::cin >> month;

using namespace boost::gregorian; try { //Use the calendar to get the last day of the month int eom_day = gregorian_calendar::end_of_month_day(year,month); date endOfMonth(year,month,eom_day);

//construct an iterator starting with firt day of the month day_iterator ditr(date(year,month,1)); //loop thru the days and print each one for (; ditr <= endOfMonth; ++ditr) { #if defined(BOOST_DATE_TIME_NO_LOCALE) std::cout << to_simple_string(*ditr) << " [" #else std::cout << *ditr << " [" #endif << ditr->day_of_week() << "]" << std::endl; } } catch(std::exception& e) {

std::cout << "Error bad date, check your entry: \n" << " Details: " << e.what() << std::endl; } return 0; }

top
Month Adding
Adding a month to a day without the use of iterators.

/* Simple program that uses the gregorian calendar to progress by exactly * one month, irregardless of how many days are in that month. * * This method can be used as an alternative to iterators */

#include "boost/date_time/gregorian/gregorian.hpp" #include <iostream>

int main() {

using namespace boost::gregorian; typedef boost::date_time::month_functor<date> add_month;

date d = day_clock::local_day(); add_month mf(1); date d2 = d + mf.get_offset(d); std::cout << "Today is: " << to_simple_string(d) << ".\n" << "One month from today will be: " << to_simple_string(d2) << std::endl;

return 0; }

top
Time Math
Various types of calculations with times and time durations.

/* Some simple examples of constructing and calculating with times * Output: * 2002-Feb-01 00:00:00 - 2002-Feb-01 05:04:02.001000000 = -5:04:02.001000000 */

#include "boost/date_time/posix_time/posix_time.hpp" #include <iostream>

int main() { using namespace boost::posix_time; using namespace boost::gregorian;

date d(2002,Feb,1); //an arbitrary date //construct a time by adding up some durations durations ptime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1)); //construct a new time by subtracting some times ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1); //construct a duration by taking the difference between times time_duration td = t2 - t1;

std::cout << to_simple_string(t2) << " - " << to_simple_string(t1) << " = " << to_simple_string(td) << std::endl;

return 0; }

top
Print Hours
Demonstrate time iteration, clock retrieval, and simple calculation.

/* Print the remaining hours of the day * Uses the clock to get the local time * Use an iterator to iterate over the remaining hours * Retrieve the date part from a time * * Expected Output something like: * * 2002-Mar-08 16:30:59 * 2002-Mar-08 17:30:59 * 2002-Mar-08 18:30:59 * 2002-Mar-08 19:30:59 * 2002-Mar-08 20:30:59 * 2002-Mar-08 21:30:59 * 2002-Mar-08 22:30:59 * 2002-Mar-08 23:30:59 * Time left till midnight: 07:29:01 */

#include "boost/date_time/posix_time/posix_time.hpp" #include <iostream>

int main() { using namespace boost::posix_time; using namespace boost::gregorian;

//get the current time from the clock -- one second resolution ptime now = second_clock::local_time(); //Get the date part out of the time date today = now.date(); date tommorrow = today + days(1); ptime tommorrow_start(tommorrow); //midnight

//iterator adds by one hour time_iterator titr(now,hours(1)); for (; titr < tommorrow_start; ++titr) { std::cout << to_simple_string(*titr) << std::endl; }

time_duration remaining = tommorrow_start - now; std::cout << "Time left till midnight: " << to_simple_string(remaining) << std::endl; return 0; }

top
Local to UTC Conversion
Demonstrate utc to local and local to utc calculations including dst.

/* Demonstrate conversions between a local time and utc * Output: * * UTC <--> New York while DST is NOT active (5 hours) * 2001-Dec-31 19:00:00 in New York is 2002-Jan-01 00:00:00 UTC time * 2002-Jan-01 00:00:00 UTC is 2001-Dec-31 19:00:00 New York time * * UTC <--> New York while DST is active (4 hours) * 2002-May-31 20:00:00 in New York is 2002-Jun-01 00:00:00 UTC time * 2002-Jun-01 00:00:00 UTC is 2002-May-31 20:00:00 New York time * * UTC <--> Arizona (7 hours) * 2002-May-31 17:00:00 in Arizona is 2002-Jun-01 00:00:00 UTC time */

#include "boost/date_time/posix_time/posix_time.hpp" #include "boost/date_time/local_time_adjustor.hpp" #include "boost/date_time/c_local_time_adjustor.hpp" #include <iostream>

int main() { using namespace boost::posix_time; using namespace boost::gregorian;

//This local adjustor depends on the machine TZ settings-- highly dangerous! typedef boost::date_time::c_local_adjustor<ptime> local_adj; ptime t10(date(2002,Jan,1), hours(7)); ptime t11 = local_adj::utc_to_local(t10); std::cout << "UTC <--> Zone base on TZ setting" << std::endl; std::cout << to_simple_string(t11) << " in your TZ is " << to_simple_string(t10) << " UTC time " << std::endl; time_duration td = t11 - t10; std::cout << "A difference of: " << to_simple_string(td) << std::endl;

//eastern timezone is utc-5 typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;

ptime t1(date(2001,Dec,31), hours(19)); //5 hours b/f midnight NY time

std::cout << "\nUTC <--> New York while DST is NOT active (5 hours)" << std::endl; ptime t2 = us_eastern::local_to_utc(t1); std::cout << to_simple_string(t1) << " in New York is " << to_simple_string(t2) << " UTC time " << std::endl;

ptime t3 = us_eastern::utc_to_local(t2);//back should be the same std::cout << to_simple_string(t2) << " UTC is " << to_simple_string(t3) << " New York time " << "\n\n";

ptime t4(date(2002,May,31), hours(20)); //4 hours b/f midnight NY time std::cout << "UTC <--> New York while DST is active (4 hours)" << std::endl; ptime t5 = us_eastern::local_to_utc(t4); std::cout << to_simple_string(t4) << " in New York is " << to_simple_string(t5) << " UTC time " << std::endl;

ptime t6 = us_eastern::utc_to_local(t5);//back should be the same std::cout << to_simple_string(t5) << " UTC is " << to_simple_string(t6) << " New York time " << "\n" << std::endl;

//Arizona timezone is utc-7 with no dst typedef boost::date_time::local_adjustor<ptime, -7, no_dst> us_arizona;

ptime t7(date(2002,May,31), hours(17)); std::cout << "UTC <--> Arizona (7 hours)" << std::endl; ptime t8 = us_arizona::local_to_utc(t7); std::cout << to_simple_string(t7) << " in Arizona is " << to_simple_string(t8) << " UTC time " << std::endl;

return 0; }

top
Time Periods
Demonstrate some simple uses of time periods.

/* Some simple examples of constructing and calculating with times * Returns: * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] contains 2002-Feb-01 03:00:05 * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] intersected with * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999] is * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999] */

#include "boost/date_time/posix_time/posix_time.hpp" #include <iostream>

using namespace boost::posix_time; using namespace boost::gregorian;

//Create a simple period class to contain all the times in a day class day_period : public time_period { public: day_period(date d) : time_period(ptime(d),//midnight ptime(d,hours(24))) {}

};

int main() {

date d(2002,Feb,1); //an arbitrary date //a period that represents a day day_period dp(d); ptime t(d, hours(3)+seconds(5)); //an arbitray time on that day if (dp.contains(t)) { std::cout << to_simple_string(dp) << " contains " << to_simple_string(t) << std::endl; } //a period that represents part of the day time_period part_of_day(ptime(d, hours(0)), t); //intersect the 2 periods and print the results if (part_of_day.intersects(dp)) { time_period result = part_of_day.intersection(dp); std::cout << to_simple_string(dp) << " intersected with\n" << to_simple_string(part_of_day) << " is \n" << to_simple_string(result) << std::endl; }

return 0; }

top
Library Reference
Library Reference
The following is a detailed reference of the date_time library. A click on any of the reference links will take you to a list of the header files found in that section. Following one of those links will take you to a list of the items declared in that header file. Further sublinks take you to detailed descriptions of each individual item.
Date Time Reference
Header <boost/date_time/adjust_functors.hpp>
namespace
boost { namespace date_time { template<typename date_type> class day_functor; template<typename date_type> class month_functor; template<typename date_type> class week_functor; template<typename date_type> class year_functor; } }
Class template day_functor
Class template day_functor -- Functor to iterate a fixed number of days.
boost::date_time::day_functor
template
<typename date_type> class day_functor { public: // types typedef date_type::duration_type duration_type;

// construct/copy/destruct
day_functor
(int);

// public member functions
duration_type get_offset(const date_type &) const; duration_type get_neg_offset(const date_type &) const; };
Description
Description
day_functor construct/copy/destruct
day_functor
construct/copy/destruct
1.
day_functor(int f);
day_functor public member functions
day_functor
public member functions
1.
duration_type get_offset(const date_type & d) const;
2.
duration_type get_neg_offset(const date_type & d) const;
Class template month_functor
Class template month_functor -- Provides calculation to find next nth month given a date.
boost::date_time::month_functor
template
<typename date_type> class month_functor { public: // types typedef date_type::duration_type duration_type; typedef date_type::calendar_type cal_type; typedef cal_type::ymd_type ymd_type; typedef cal_type::day_type day_type;

// construct/copy/destruct
month_functor
(int);

// public member functions
duration_type get_offset(const date_type &) const; duration_type get_neg_offset(const date_type &) const; };
Description
Description
This adjustment function provides the logic for 'month-based' advancement on a ymd based calendar. The policy it uses to handle the non existant end of month days is to back up to the last day of the month. Also, if the starting date is the last day of a month, this functor will attempt to adjust to the end of the month.
month_functor construct/copy/destruct
month_functor
construct/copy/destruct
1.
month_functor(int f);
month_functor public member functions
month_functor
public member functions
1.
duration_type get_offset(const date_type & d) const;
2.
duration_type get_neg_offset(const date_type & d) const;
Returns a negative duration_type.
Class template week_functor
Class template week_functor -- Functor to iterate a over weeks.
boost::date_time::week_functor
template
<typename date_type> class week_functor { public: // types typedef date_type::duration_type duration_type; typedef date_type::calendar_type calendar_type;

// construct/copy/destruct
week_functor
(int);

// public member functions
duration_type get_offset(const date_type &) const; duration_type get_neg_offset(const date_type &) const; };
Description
Description
week_functor construct/copy/destruct
week_functor
construct/copy/destruct
1.
week_functor(int f);
week_functor public member functions
week_functor
public member functions
1.
duration_type get_offset(const date_type & d) const;
2.
duration_type get_neg_offset(const date_type & d) const;
Class template year_functor
Class template year_functor -- Functor to iterate by a year adjusting for leap years.
boost::date_time::year_functor
template
<typename date_type> class year_functor { public: // types typedef date_type::duration_type duration_type;

// construct/copy/destruct
year_functor
(int);

// public member functions
duration_type get_offset(const date_type &) const; duration_type get_neg_offset(const date_type &) const; };
Description
Description
year_functor construct/copy/destruct
year_functor
construct/copy/destruct
1.
year_functor(int f);
year_functor public member functions
year_functor
public member functions
1.
duration_type get_offset(const date_type & d) const;
2.
duration_type get_neg_offset(const date_type & d) const;
Header <boost/date_time/c_local_time_adjustor.hpp>
Time adjustment calculations based on machine
namespace
boost { namespace date_time { template<typename time_type> class c_local_adjustor; } }
Class template c_local_adjustor
Class template c_local_adjustor -- Adjust to / from utc using the C API.
boost::date_time::c_local_adjustor
template
<typename time_type> class c_local_adjustor { public: // types typedef time_type::time_duration_type time_duration_type; typedef time_type::date_type date_type; typedef date_type::duration_type date_duration_type;

// public static functions
time_type utc_to_local(const time_type &) ; };
Description
Description
Warning!!! This class assumes that timezone settings of the machine are correct. This can be a very dangerous assumption.
c_local_adjustor public static functions
c_local_adjustor
public static functions
1.
time_type utc_to_local(const time_type & t) ;
Convert a utc time to local time.
Header <boost/date_time/c_time.hpp>
Provide workarounds related to the ctime header
namespace
std { }
Header <boost/date_time/compiler_config.hpp>
namespace
std { }
Header <boost/date_time/constrained_value.hpp>
namespace
boost { namespace CV { template<typename value_policies> class constrained_value; template<typename rep_type, rep_type min_value, rep_type max_value, typename exception_type> class simple_exception_policy;

// Represent a min or max violation type.
enum
violation_enum { min_violation, max_violation }; } }
Class template constrained_value
Class template constrained_value -- A template to specify a constrained basic value type.
boost::CV::constrained_value
template
<typename value_policies> class constrained_value { public: // types typedef value_policies::value_type value_type;

// construct/copy/destruct
constrained_value
(value_type); constrained_value& operator=(value_type);

// public member functions
operator
value_type
() const;

// public static functions
value_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ; value_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;

// private member functions
void
assign
(value_type) ; };
Description
Description
This template provides a quick way to generate an integer type with a constrained range. The type provides for the ability to specify the min, max, and and error handling policy.
value policies
A class that provides the range limits via the min and max functions as well as a function on_error that determines how errors are handled. A common strategy would be to assert or throw and exception. The on_error is passed both the current value and the new value that is in error.
constrained_value construct/copy/destruct
constrained_value
construct/copy/destruct
1.
constrained_value(value_type value);
2.
constrained_value& operator=(value_type v);
constrained_value public member functions
constrained_value
public member functions
1.
operator
value_type() const;
Coerce into the representation type.
constrained_value public static functions
constrained_value
public static functions
1.
value_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;
Return the max allowed value (traits method).
2.
value_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;
Return the min allowed value (traits method).
constrained_value private member functions
constrained_value
private member functions
1.
void
assign(value_type value) ;
Class template simple_exception_policy
Class template simple_exception_policy -- Template to shortcut the constrained_value policy creation process.
boost::CV::simple_exception_policy
template
<typename rep_type, rep_type min_value, rep_type max_value, typename exception_type> class simple_exception_policy { public: // types typedef rep_type value_type;

// public static functions
rep_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ; rep_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ; void on_error(rep_type, rep_type, violation_enum) ; };
Description
Description
simple_exception_policy public static functions
simple_exception_policy
public static functions
1.
rep_type min BOOST_PREVENT_MACRO_SUBSTITUTION() ;
2.
rep_type max BOOST_PREVENT_MACRO_SUBSTITUTION() ;
3.
void
on_error(rep_type , rep_type , violation_enum ) ;
Header <boost/date_time/date.hpp>
namespace
boost { namespace date_time { template<typename T, typename calendar, typename duration_type_> class date; } }
Class template date
Class template date -- Representation of timepoint at the one day level resolution.
boost::date_time::date
template
<typename T, typename calendar, typename duration_type_> class date { public: // types typedef T date_type; typedef calendar calendar_type; typedef calendar::date_traits_type traits_type; typedef duration_type_ duration_type; typedef calendar::year_type year_type; typedef calendar::month_type month_type; typedef calendar::day_type day_type; typedef calendar::ymd_type ymd_type; typedef calendar::date_rep_type date_rep_type; typedef calendar::date_int_type date_int_type; typedef calendar::day_of_week_type day_of_week_type;

// construct/copy/destruct
date
(year_type, month_type, day_type); date(const ymd_type &); date(date_int_type); date(date_rep_type);

// public member functions
year_type year() const; month_type month() const; day_type day() const; day_of_week_type day_of_week() const; ymd_type year_month_day() const; bool operator<(const date_type &) const; bool operator==(const date_type &) const; bool is_special() const; bool is_not_a_date() const; bool is_infinity() const; bool is_pos_infinity() const; bool is_neg_infinity() const; special_values as_special() const; duration_type operator-(const date_type &) const; date_type operator-(const duration_type &) const; date_type operator-=(const duration_type &) ; date_rep_type day_count() const; date_type operator+(const duration_type &) const; date_type operator+=(const duration_type &) ;

// protected member functions
};
Description
Description
The date template represents an interface shell for a date class that is based on a year-month-day system such as the gregorian or iso systems. It provides basic operations to enable calculation and comparisons.
Theory
This date representation fundamentally departs from the C tm struct approach. The goal for this type is to provide efficient date operations (add, subtract) and storage (minimize space to represent) in a concrete class. Thus, the date uses a count internally to represent a particular date. The calendar parameter defines the policies for converting the the year-month-day and internal counted form here. Applications that need to perform heavy formatting of the same date repeatedly will perform better by using the year-month-day representation.
Internally the date uses a day number to represent the date. This is a monotonic time representation. This representation allows for fast comparison as well as simplifying the creation of writing numeric operations. Essentially, the internal day number is like adjusted julian day. The adjustment is determined by the Epoch date which is represented as day 1 of the calendar. Day 0 is reserved for negative infinity so that any actual date is automatically greater than negative infinity. When a date is constructed from a date or formatted for output, the appropriate conversions are applied to create the year, month, day representations.
date construct/copy/destruct
date
construct/copy/destruct
1.
date(year_type y, month_type m, day_type d);
2.
date(const ymd_type & ymd);
3.
date(date_int_type days);
This is a private constructor which allows for the creation of new dates. It is not exposed to users since that would require class users to understand the inner workings of the date class.
4.
date(date_rep_type days);
date public member functions
date
public member functions
1.
year_type year() const;
2.
month_type month() const;
3.
day_type day() const;
4.
day_of_week_type day_of_week() const;
5.
ymd_type year_month_day() const;
6.
bool
operator
<(const date_type & rhs) const;
7.
bool
operator
==(const date_type & rhs) const;
8.
bool
is_special() const;
check to see if date is a special value
9.
bool
is_not_a_date() const;
check to see if date is not a value
10.
bool
is_infinity() const;
check to see if date is one of the infinity values
11.
bool
is_pos_infinity() const;
check to see if date is greater than all possible dates
12.
bool
is_neg_infinity() const;
check to see if date is greater than all possible dates
13.
special_values as_special() const;
return as a special value or a not_special if a normal date
14.
duration_type operator-(const date_type & d) const;
15.
date_type operator-(const duration_type & dd) const;
16.
date_type operator-=(const duration_type & dd) ;
17.
date_rep_type day_count() const;
18.
date_type operator+(const duration_type & dd) const;
19.
date_type operator+=(const duration_type & dd) ;
date protected member functions
date
protected member functions
Header <boost/date_time/date_clock_device.hpp>
namespace
boost { namespace date_time { template<typename date_type> class day_clock; } }
Class template day_clock
Class template day_clock -- A clock providing day level services based on C time_t capabilities.
boost::date_time::day_clock
template
<typename date_type> class day_clock { public: // types typedef date_type::ymd_type ymd_type;

// public static functions
date_type local_day() ; date_type::ymd_type local_day_ymd() ; date_type::ymd_type universal_day_ymd() ; date_type universal_day() ;

// private static functions
::std::tm * get_local_time() ; ::std::tm * get_universal_time() ; };
Description
Description
This clock uses Posix interfaces as its implementation and hence uses the timezone settings of the operating system. Incorrect user settings will result in incorrect results for the calls to local_day.
day_clock public static functions
day_clock
public static functions
1.
date_type local_day() ;
Get the local day as a date type.
2.
date_type::ymd_type local_day_ymd() ;
Get the local day as a ymd_type.
3.
date_type::ymd_type universal_day_ymd() ;
Get the current day in universal date as a ymd_type.
4.
date_type universal_day() ;
Get the UTC day as a date type.
day_clock private static functions
day_clock
private static functions
1.
::std::tm * get_local_time() ;
2.
::std::tm * get_universal_time() ;
Header <boost/date_time/date_defs.hpp>
namespace
boost { namespace date_time {

// An enumeration of weekday names.
enum
weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

// Simple enum to allow for nice programming with Jan, Feb, etc.
enum
months_of_year { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, NotAMonth, NumMonths }; } }
Header <boost/date_time/date_duration.hpp>
namespace
boost { namespace date_time { template<typename duration_rep_traits> class date_duration;

struct
duration_traits_long
; struct duration_traits_adapted; } }
Class template date_duration
Class template date_duration -- Duration type with date level resolution.
boost::date_time::date_duration
template
<typename duration_rep_traits> class date_duration { public: // types typedef duration_rep_traits::int_type duration_rep_type; typedef duration_rep_traits::impl_type duration_rep;

// construct/copy/destruct
date_duration
(duration_rep); date_duration(special_values); date_duration(const date_duration< duration_rep_traits > &);

// public member functions
duration_rep get_rep() const; bool is_special() const; duration_rep_type days() const; bool operator==(const date_duration &) const; bool operator<(const date_duration &) const; date_duration operator-=(const date_duration &) ; date_duration operator+=(const date_duration &) ; date_duration operator-() const; date_duration< duration_rep_traits > operator/=(int) ; date_duration< duration_rep_traits > operator/(int) ; bool is_negative() const;

// public static functions
date_duration
unit
() ; };
Description
Description
date_duration construct/copy/destruct
date_duration
construct/copy/destruct
1.
date_duration(duration_rep day_count);
Construct from a day count.
2.
date_duration(special_values sv);
construct from special_values - only works when instantiated with duration_traits_adapted
3.
date_duration(const date_duration< duration_rep_traits > & other);
Construct from another date_duration (Copy Constructor).
date_duration public member functions
date_duration
public member functions
1.
duration_rep get_rep() const;
returns days_ as it's instantiated type - used for streaming
2.
bool
is_special() const;
3.
duration_rep_type days() const;
returns days as value, not object.
4.
bool
operator
==(const date_duration & rhs) const;
Equality.
5.
bool
operator
<(const date_duration & rhs) const;
Less.
6.
date_duration
operator
-=(const date_duration & rhs) ;
Subtract another duration -- result is signed.
7.
date_duration
operator
+=(const date_duration & rhs) ;
Add a duration -- result is signed.
8.
date_duration
operator
-() const;
unary- Allows for dd = -date_duration(2); -> dd == -2
9.
date_duration
< duration_rep_traits > operator/=(int divisor) ;
Division operations on a duration with an integer.
10.
date_duration
< duration_rep_traits > operator/(int divisor) ;
11.
bool
is_negative() const;
return sign information
date_duration public static functions
date_duration
public static functions
1.
date_duration
unit() ;
Returns the smallest duration -- used by to calculate 'end'.
Struct duration_traits_long
Struct duration_traits_long --
boost::date_time::duration_traits_long
struct
duration_traits_long { // types typedef long int_type; typedef long impl_type;

// public static functions
int_type as_number(impl_type) ; };
Description
Description
Struct for instantiating date_duration with NO special values functionality. Allows for transparent implementation of either date_duration<long> or date_duration<int_adapter<long> >
duration_traits_long public static functions
duration_traits_long
public static functions
1.
int_type as_number(impl_type i) ;
Struct duration_traits_adapted
Struct duration_traits_adapted --
boost::date_time::duration_traits_adapted
struct
duration_traits_adapted { // types typedef long int_type; typedef boost::date_time::int_adapter< long > impl_type;

// public static functions
int_type as_number(impl_type) ; };
Description
Description
Struct for instantiating date_duration WITH special values functionality. Allows for transparent implementation of either date_duration<long> or date_duration<int_adapter<long> >
duration_traits_adapted public static functions
duration_traits_adapted
public static functions
1.
int_type as_number(impl_type i) ;
Header <boost/date_time/date_duration_types.hpp>
namespace
boost { namespace date_time { template<typename duration_config> class weeks_duration; template<typename base_config> class months_duration; template<typename base_config> class years_duration; } }
Class template weeks_duration
Class template weeks_duration -- Additional duration type that represents a number of n*7 days.
boost::date_time::weeks_duration
template
<typename duration_config> class weeks_duration : : public boost::date_time::date_duration< duration_config > { public: // construct/copy/destruct weeks_duration(typename duration_config::impl_type); weeks_duration(special_values);

// public member functions
};
Description
Description
weeks_duration construct/copy/destruct
weeks_duration
construct/copy/destruct
1.
weeks_duration(typename duration_config::impl_type w);
2.
weeks_duration(special_values sv);
weeks_duration public member functions
weeks_duration
public member functions
Class template months_duration
Class template months_duration -- additional duration type that represents a logical month
boost::date_time::months_duration
template
<typename base_config> class months_duration { public: // construct/copy/destruct months_duration(int_rep); months_duration(special_values);

// public member functions
int_rep number_of_months() const; duration_type get_neg_offset(const date_type &) const; duration_type get_offset(const date_type &) const; bool operator==(const months_type &) const; bool operator!=(const months_type &) const; months_type operator+(const months_type &) const; months_type & operator+=(const months_type &) ; months_type operator-(const months_type &) const; months_type & operator-=(const months_type &) ; months_type operator *(const int_type) const; months_type & operator *=(const int_type) ; months_type operator/(const int_type) const; months_type & operator/=(const int_type) ; months_type operator+(const years_type &) const; months_type & operator+=(const years_type &) ; months_type operator-(const years_type &) const; months_type & operator-=(const years_type &) ; };
Description
Description
A logical month enables things like: "date(2002,Mar,2) + months(2) -> 2002-May2". If the date is a last day-of-the-month, the result will also be a last-day-of-the-month.
months_duration construct/copy/destruct
months_duration
construct/copy/destruct
1.
months_duration(int_rep num);
2.
months_duration(special_values sv);
months_duration public member functions
months_duration
public member functions
1.
int_rep number_of_months() const;
2.
duration_type get_neg_offset(const date_type & d) const;
returns a negative duration
3.
duration_type get_offset(const date_type & d) const;
4.
bool
operator
==(const months_type & rhs) const;
5.
bool
operator
!=(const months_type & rhs) const;
6.
months_type operator+(const months_type & rhs) const;
7.
months_type & operator+=(const months_type & rhs) ;
8.
months_type operator-(const months_type & rhs) const;
9.
months_type & operator-=(const months_type & rhs) ;
10.
months_type operator *(const int_type rhs) const;
11.
months_type & operator *=(const int_type rhs) ;
12.
months_type operator/(const int_type rhs) const;
13.
months_type & operator/=(const int_type rhs) ;
14.
months_type operator+(const years_type & y) const;
15.
months_type & operator+=(const years_type & y) ;
16.
months_type operator-(const years_type & y) const;
17.
months_type & operator-=(const years_type & y) ;
Class template years_duration
Class template years_duration -- additional duration type that represents a logical year
boost::date_time::years_duration
template
<typename base_config> class years_duration { public: // construct/copy/destruct years_duration(int_rep); years_duration(special_values);

// public member functions
int_rep number_of_years() const; duration_type get_neg_offset(const date_type &) const; duration_type get_offset(const date_type &) const; bool operator==(const years_type &) const; bool operator!=(const years_type &) const; years_type operator+(const years_type &) const; years_type & operator+=(const years_type &) ; years_type operator-(const years_type &) const; years_type & operator-=(const years_type &) ; years_type operator *(const int_type) const; years_type & operator *=(const int_type) ; years_type operator/(const int_type) const; years_type & operator/=(const int_type) ; months_type operator+(const months_type &) const; months_type operator-(const months_type &) const; };
Description
Description
A logical year enables things like: "date(2002,Mar,2) + years(2) -> 2004-Mar-2". If the date is a last day-of-the-month, the result will also be a last-day-of-the-month (ie date(2001-Feb-28) + years(3) -> 2004-Feb-29).
years_duration construct/copy/destruct
years_duration
construct/copy/destruct
1.
years_duration(int_rep num);
2.
years_duration(special_values sv);
years_duration public member functions
years_duration
public member functions
1.
int_rep number_of_years() const;
2.
duration_type get_neg_offset(const date_type & d) const;
returns a negative duration
3.
duration_type get_offset(const date_type & d) const;
4.
bool
operator
==(const years_type & rhs) const;
5.
bool
operator
!=(const years_type & rhs) const;
6.
years_type operator+(const years_type & rhs) const;
7.
years_type & operator+=(const years_type & rhs) ;
8.
years_type operator-(const years_type & rhs) const;
9.
years_type & operator-=(const years_type & rhs) ;
10.
years_type operator *(const int_type rhs) const;
11.
years_type & operator *=(const int_type rhs) ;
12.
years_type operator/(const int_type rhs) const;
13.
years_type & operator/=(const int_type rhs) ;
14.
months_type operator+(const months_type & m) const;
15.
months_type operator-(const months_type & m) const;
Header <boost/date_time/date_format_simple.hpp>
namespace
boost { namespace date_time { template<typename charT> class simple_format;

template
<> class simple_format<wchar_t>; } }
Class template simple_format
Class template simple_format -- Class to provide simple basic formatting rules.
boost::date_time::simple_format
template
<typename charT> class simple_format { public:

// public static functions
const
charT * not_a_date() ; const charT * pos_infinity() ; const charT * neg_infinity() ; month_format_spec month_format() ; ymd_order_spec date_order() ; bool has_date_sep_chars() ; charT year_sep_char() ; charT month_sep_char() ; charT day_sep_char() ; charT hour_sep_char() ; charT minute_sep_char() ; charT second_sep_char() ; };
Description
Description
simple_format public static functions
simple_format
public static functions
1.
const
charT * not_a_date() ;
String used printed is date is invalid.
2.
const
charT * pos_infinity() ;
String used to for positive infinity value.
3.
const
charT * neg_infinity() ;
String used to for positive infinity value.
4.
month_format_spec month_format() ;
Describe month format.
5.
ymd_order_spec date_order() ;
6.
bool
has_date_sep_chars() ;
This format uses '-' to separate date elements.
7.
charT year_sep_char() ;
Char to sep?
8.
charT month_sep_char() ;
char between year-month
9.
charT day_sep_char() ;
Char to separate month-day.
10.
charT hour_sep_char() ;
char between date-hours
11.
charT minute_sep_char() ;
char between hour and minute
12.
charT second_sep_char() ;
char for second
Specializations
Specializations
•
Class simple_format<wchar_t>
Class simple_format<wchar_t>
Class simple_format<wchar_t> -- Specialization of formmating rules for wchar_t.
boost::date_time::simple_format<wchar_t>
class
simple_format<wchar_t> { public:

// public static functions
const
wchar_t
* not_a_date() ; const wchar_t * pos_infinity() ; const wchar_t * neg_infinity() ; month_format_spec month_format() ; ymd_order_spec date_order() ; bool has_date_sep_chars() ; wchar_t year_sep_char() ; wchar_t month_sep_char() ; wchar_t day_sep_char() ; wchar_t hour_sep_char() ; wchar_t minute_sep_char() ; wchar_t second_sep_char() ; };
Description
Description
simple_format public static functions
simple_format
public static functions
1.
const
wchar_t
* not_a_date() ;
String used printed is date is invalid.
2.
const
wchar_t
* pos_infinity() ;
String used to for positive infinity value.
3.
const
wchar_t
* neg_infinity() ;
String used to for positive infinity value.
4.
month_format_spec month_format() ;
Describe month format.
5.
ymd_order_spec date_order() ;
6.
bool
has_date_sep_chars() ;
This format uses '-' to separate date elements.
7.
wchar_t
year_sep_char() ;
Char to sep?
8.
wchar_t
month_sep_char() ;
char between year-month
9.
wchar_t
day_sep_char() ;
Char to separate month-day.
10.
wchar_t
hour_sep_char() ;
char between date-hours
11.
wchar_t
minute_sep_char() ;
char between hour and minute
12.
wchar_t
second_sep_char() ;
char for second
Header <boost/date_time/date_formatting.hpp>
namespace
boost { namespace date_time { template<typename month_type, typename format_type, typename charT = char> class month_formatter; template<typename ymd_type, typename format_type, typename charT = char> class ymd_formatter; template<typename date_type, typename format_type, typename charT = char> class date_formatter; } }
Class template month_formatter
Class template month_formatter -- Formats a month as as string into an ostream.
boost::date_time::month_formatter
template
<typename month_type, typename format_type, typename charT = char> class month_formatter { public:

// public static functions
std::basic_ostream< charT > & format_month(const month_type &, std::basic_ostream< charT > &) ; std::ostream & format_month(const month_type &, std::ostream &) ; };
Description
Description
month_formatter public static functions
month_formatter
public static functions
1.
std::basic_ostream< charT > & format_month(const month_type & month, std::basic_ostream< charT > & os) ;
Formats a month as as string into an ostream.
This function demands that month_type provide functions for converting to short and long strings if that capability is used.
2.
std::ostream & format_month(const month_type & month, std::ostream & os) ;
Formats a month as as string into an ostream.
This function demands that month_type provide functions for converting to short and long strings if that capability is used.
Class template ymd_formatter
Class template ymd_formatter -- Convert ymd to a standard string formatting policies.
boost::date_time::ymd_formatter
template
<typename ymd_type, typename format_type, typename charT = char> class ymd_formatter { public:

// public static functions
std::basic_string< charT > ymd_to_string(ymd_type) ; std::string ymd_to_string(ymd_type) ; };
Description
Description
ymd_formatter public static functions
ymd_formatter
public static functions
1.
std::basic_string< charT > ymd_to_string(ymd_type ymd) ;
Convert ymd to a standard string formatting policies.
This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy
2.
std::string ymd_to_string(ymd_type ymd) ;
Convert ymd to a standard string formatting policies.
This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy
Class template date_formatter
Class template date_formatter -- Convert a date to string using format policies.
boost::date_time::date_formatter
template
<typename date_type, typename format_type, typename charT = char> class date_formatter { public: // types typedef std::basic_string< charT > string_type;

// public static functions
string_type date_to_string(date_type) ; std::string date_to_string(date_type) ; };
Description
Description
date_formatter public static functions
date_formatter
public static functions
1.
string_type date_to_string(date_type d) ;
Convert to a date to standard string using format policies.
2.
std::string date_to_string(date_type d) ;
Convert to a date to standard string using format policies.
Header <boost/date_time/date_formatting_limited.hpp>
namespace
boost { namespace date_time { } }
Header <boost/date_time/date_formatting_locales.hpp>
namespace
boost { namespace date_time { template<typename facet_type, typename charT = char> class ostream_month_formatter; template<typename weekday_type, typename facet_type, typename charT = char> class ostream_weekday_formatter; template<typename ymd_type, typename facet_type, typename charT = char> class ostream_ymd_formatter; template<typename date_type, typename facet_type, typename charT = char> class ostream_date_formatter; } }
Class template ostream_month_formatter
Class template ostream_month_formatter -- Formats a month as as string into an ostream.
boost::date_time::ostream_month_formatter
template
<typename facet_type, typename charT = char> class ostream_month_formatter { public: // types typedef facet_type::month_type month_type; typedef std::basic_ostream< charT > ostream_type;

// public static functions
void
format_month
(const month_type &, ostream_type &, const facet_type &) ; };
Description
Description
ostream_month_formatter public static functions
ostream_month_formatter
public static functions
1.
void
format_month(const month_type & month, ostream_type & os, const facet_type & f) ;
Formats a month as as string into an output iterator.
Class template ostream_weekday_formatter
Class template ostream_weekday_formatter -- Formats a weekday.
boost::date_time::ostream_weekday_formatter
template
<typename weekday_type, typename facet_type, typename charT = char> class ostream_weekday_formatter { public: // types typedef facet_type::month_type month_type; typedef std::basic_ostream< charT > ostream_type;

// public static functions
void
format_weekday
(const weekday_type &, ostream_type &, const facet_type &, bool) ; };
Description
Description
ostream_weekday_formatter public static functions
ostream_weekday_formatter
public static functions
1.
void
format_weekday(const weekday_type & wd, ostream_type & os, const facet_type & f, bool as_long_string) ;
Formats a month as as string into an output iterator.
Class template ostream_ymd_formatter
Class template ostream_ymd_formatter -- Convert ymd to a standard string formatting policies.
boost::date_time::ostream_ymd_formatter
template
<typename ymd_type, typename facet_type, typename charT = char> class ostream_ymd_formatter { public: // types typedef ymd_type::month_type month_type; typedef ostream_month_formatter< facet_type, charT > month_formatter_type; typedef std::basic_ostream< charT > ostream_type; typedef std::basic_string< charT > foo_type;

// public static functions
void
ymd_put
(ymd_type, ostream_type &, const facet_type &) ; };
Description
Description
ostream_ymd_formatter public static functions
ostream_ymd_formatter
public static functions
1.
void
ymd_put(ymd_type ymd, ostream_type & os, const facet_type & f) ;
Convert ymd to a standard string formatting policies.
This is standard code for handling date formatting with year-month-day based date information. This function uses the format_type to control whether the string will contain separator characters, and if so what the character will be. In addtion, it can format the month as either an integer or a string as controled by the formatting policy
Class template ostream_date_formatter
Class template ostream_date_formatter -- Convert a date to string using format policies.
boost::date_time::ostream_date_formatter
template
<typename date_type, typename facet_type, typename charT = char> class ostream_date_formatter { public: // types typedef std::basic_ostream< charT > ostream_type; typedef date_type::ymd_type ymd_type;

// public static functions
void
date_put
(const date_type &, ostream_type &, const facet_type &) ; void date_put(const date_type &, ostream_type &) ; };
Description
Description
ostream_date_formatter public static functions
ostream_date_formatter
public static functions
1.
void
date_put(const date_type & d, ostream_type & os, const facet_type & f) ;
Put date into an ostream.
2.
void
date_put(const date_type & d, ostream_type & os) ;
Put date into an ostream.
Header <boost/date_time/date_generators.hpp>
Definition and implementation of date algorithm templates
namespace
boost { namespace date_time { template<typename date_type> class year_based_generator; template<typename date_type> class partial_date; template<typename date_type> class nth_kday_of_month; template<typename date_type> class first_kday_of_month; template<typename date_type> class last_kday_of_month; template<typename date_type> class first_kday_after; template<typename date_type> class first_kday_before;

// Returns nth arg as string. 1 -> "first", 2 -> "second", max is 5.
BOOST_DATE_TIME_DECL const char * nth_as_str(int n); template<typename date_type, typename weekday_type> date_type::duration_type days_until_weekday(const date_type &, const weekday_type &); template<typename date_type, typename weekday_type> date_type::duration_type days_before_weekday(const date_type &, const weekday_type &); template<typename date_type, typename weekday_type> date_type next_weekday(const date_type &, const weekday_type &); template<typename date_type, typename weekday_type> date_type previous_weekday(const date_type &, const weekday_type &); } }
Class template year_based_generator
Class template year_based_generator -- Base class for all generators that take a year and produce a date.
boost::date_time::year_based_generator
template
<typename date_type> class year_based_generator { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::year_type year_type;

// construct/copy/destruct
year_based_generator
(); ~year_based_generator();

// public member functions
virtual
date_type get_date(year_type) const; };
Description
Description
This class is a base class for polymorphic function objects that take a year and produce a concrete date.
year_based_generator construct/copy/destruct
year_based_generator
construct/copy/destruct
1.
year_based_generator();
2.
~year_based_generator();
year_based_generator public member functions
year_based_generator
public member functions
1.
virtual
date_type get_date(year_type y) const;
Class template partial_date
Class template partial_date -- Generates a date by applying the year to the given month and day.
boost::date_time::partial_date
template
<typename date_type> class partial_date : : public boost::date_time::year_based_generator< date_type > { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_type day_type; typedef calendar_type::month_type month_type; typedef calendar_type::year_type year_type; typedef date_type::duration_type duration_type; typedef duration_type::duration_rep duration_rep;

// construct/copy/destruct
partial_date
(day_type, month_type); partial_date(duration_rep);

// public member functions
date_type get_date(year_type) const; date_type operator()(year_type) const; bool operator==(const partial_date &) const; bool operator<(const partial_date &) const; month_type month() const; day_type day() const; };
Description
Description
Example usage: partial_date pd(1, Jan); partial_date pd2(70); date d = pd.get_date(2002); //2002-Jan-01 date d2 = pd2.get_date(2002); //2002-Mar-10
partial_date construct/copy/destruct
partial_date
construct/copy/destruct
1.
partial_date(day_type d, month_type m);
2.
partial_date(duration_rep days);
Partial date created from number of days into year. Range 1-366.
Allowable values range from 1 to 366. 1=Jan1, 366=Dec31. If argument exceeds range, partial_date will be created with closest in-range value. 60 will always be Feb29, if get_date() is called with a non-leap year an exception will be thrown
partial_date public member functions
partial_date
public member functions
1.
date_type get_date(year_type y) const;
Return a concrete date when provided with a year specific year.
Will throw an 'invalid_argument' exception if a partial_date object, instantiated with Feb-29, has get_date called with a non-leap year. Example: partial_date pd(29, Feb); pd.get_date(2003); // throws invalid_argument exception pg.get_date(2000); // returns 2000-2-29
2.
date_type operator()(year_type y) const;
3.
bool
operator
==(const partial_date & rhs) const;
4.
bool
operator
<(const partial_date & rhs) const;
5.
month_type month() const;
6.
day_type day() const;
Class template nth_kday_of_month
Class template nth_kday_of_month -- Useful generator functor for finding holidays.
boost::date_time::nth_kday_of_month
template
<typename date_type> class nth_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_of_week_type day_of_week_type; typedef calendar_type::month_type month_type; typedef calendar_type::year_type year_type; typedef date_type::duration_type duration_type;

// construct/copy/destruct
nth_kday_of_month
(week_num, day_of_week_type, month_type);

// public member functions
date_type get_date(year_type) const; month_type month() const; week_num nth_week() const; day_of_week_type day_of_week() const; const char * nth_week_as_str() const; };
Description
Description
Based on the idea in Cal. Calc. for finding holidays that are the 'first Monday of September'. When instantiated with 'fifth' kday of month, the result will be the last kday of month which can be the fourth or fifth depending on the structure of the month.
The algorithm here basically guesses for the first day of the month. Then finds the first day of the correct type. That is, if the first of the month is a Tuesday and it needs Wenesday then we simply increment by a day and then we can add the length of a week until we get to the 'nth kday'. There are probably more efficient algorithms based on using a mod 7, but this one works reasonably well for basic applications.
nth_kday_of_month construct/copy/destruct
nth_kday_of_month
construct/copy/destruct
1.
nth_kday_of_month(week_num week_no, day_of_week_type dow, month_type m);
nth_kday_of_month public member functions
nth_kday_of_month
public member functions
1.
date_type get_date(year_type y) const;
Return a concrete date when provided with a year specific year.
2.
month_type month() const;
3.
week_num nth_week() const;
4.
day_of_week_type day_of_week() const;
5.
const
char
* nth_week_as_str() const;
Class template first_kday_of_month
Class template first_kday_of_month -- Useful generator functor for finding holidays and daylight savings.
boost::date_time::first_kday_of_month
template
<typename date_type> class first_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_of_week_type day_of_week_type; typedef calendar_type::month_type month_type; typedef calendar_type::year_type year_type; typedef date_type::duration_type duration_type;

// construct/copy/destruct
first_kday_of_month
(day_of_week_type, month_type);

// public member functions
date_type get_date(year_type) const; month_type month() const; day_of_week_type day_of_week() const; };
Description
Description
Similar to nth_kday_of_month, but requires less paramters
first_kday_of_month construct/copy/destruct
first_kday_of_month
construct/copy/destruct
1.
first_kday_of_month(day_of_week_type dow, month_type m);
Specify the first 'Sunday' in 'April' spec.
Parameters
dow
The day of week, eg: Sunday, Monday, etc
m
The month of the year, eg: Jan, Feb, Mar, etc
first_kday_of_month public member functions
first_kday_of_month
public member functions
1.
date_type get_date(year_type year) const;
Return a concrete date when provided with a year specific year.
2.
month_type month() const;
3.
day_of_week_type day_of_week() const;
Class template last_kday_of_month
Class template last_kday_of_month -- Calculate something like Last Sunday of January.
boost::date_time::last_kday_of_month
template
<typename date_type> class last_kday_of_month : : public boost::date_time::year_based_generator< date_type > { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_of_week_type day_of_week_type; typedef calendar_type::month_type month_type; typedef calendar_type::year_type year_type; typedef date_type::duration_type duration_type;

// construct/copy/destruct
last_kday_of_month
(day_of_week_type, month_type);

// public member functions
date_type get_date(year_type) const; month_type month() const; day_of_week_type day_of_week() const; };
Description
Description
Useful generator functor for finding holidays and daylight savings Get the last day of the month and then calculate the difference to the last previous day.
last_kday_of_month construct/copy/destruct
last_kday_of_month
construct/copy/destruct
1.
last_kday_of_month(day_of_week_type dow, month_type m);
Specify the date spec like last 'Sunday' in 'April' spec.
Parameters
dow
The day of week, eg: Sunday, Monday, etc
m
The month of the year, eg: Jan, Feb, Mar, etc
last_kday_of_month public member functions
last_kday_of_month
public member functions
1.
date_type get_date(year_type year) const;
Return a concrete date when provided with a year specific year.
2.
month_type month() const;
3.
day_of_week_type day_of_week() const;
Class template first_kday_after
Class template first_kday_after -- Calculate something like "First Sunday after Jan 1,2002.
boost::date_time::first_kday_after
template
<typename date_type> class first_kday_after { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_of_week_type day_of_week_type; typedef date_type::duration_type duration_type;

// construct/copy/destruct
first_kday_after
(day_of_week_type);

// public member functions
date_type get_date(date_type) const; day_of_week_type day_of_week() const; };
Description
Description
Date generator that takes a date and finds kday after typedef boost::date_time::first_kday_after<date> firstkdayafter; firstkdayafter fkaf(Monday); fkaf.get_date(date(2002,Feb,1));
first_kday_after construct/copy/destruct
first_kday_after
construct/copy/destruct
1.
first_kday_after(day_of_week_type dow);
first_kday_after public member functions
first_kday_after
public member functions
1.
date_type get_date(date_type start_day) const;
Return next kday given.
2.
day_of_week_type day_of_week() const;
Class template first_kday_before
Class template first_kday_before -- Calculate something like "First Sunday before Jan 1,2002.
boost::date_time::first_kday_before
template
<typename date_type> class first_kday_before { public: // types typedef date_type::calendar_type calendar_type; typedef calendar_type::day_of_week_type day_of_week_type; typedef date_type::duration_type duration_type;

// construct/copy/destruct
first_kday_before
(day_of_week_type);

// public member functions
date_type get_date(date_type) const; day_of_week_type day_of_week() const; };
Description
Description
Date generator that takes a date and finds kday after typedef boost::date_time::first_kday_before<date> firstkdaybefore; firstkdaybefore fkbf(Monday); fkbf.get_date(date(2002,Feb,1));
first_kday_before construct/copy/destruct
first_kday_before
construct/copy/destruct
1.
first_kday_before(day_of_week_type dow);
first_kday_before public member functions
first_kday_before
public member functions
1.
date_type get_date(date_type start_day) const;
Return next kday given.
2.
day_of_week_type day_of_week() const;
Function template days_until_weekday
Function template days_until_weekday -- Calculates the number of days until the next weekday.
boost::date_time::days_until_weekday
template
<typename date_type, typename weekday_type> date_type::duration_type days_until_weekday(const date_type & d, const weekday_type & wd);
Description
Description
Calculates the number of days until the next weekday. If the date given falls on a Sunday and the given weekday is Tuesday the result will be 2 days
Function template days_before_weekday
Function template days_before_weekday -- Calculates the number of days since the previous weekday.
boost::date_time::days_before_weekday
template
<typename date_type, typename weekday_type> date_type::duration_type days_before_weekday(const date_type & d, const weekday_type & wd);
Description
Description
Calculates the number of days since the previous weekday If the date given falls on a Sunday and the given weekday is Tuesday the result will be 5 days. The answer will be a positive number because Tuesday is 5 days before Sunday, not -5 days before.
Function template next_weekday
Function template next_weekday -- Generates a date object representing the date of the following weekday from the given date.
boost::date_time::next_weekday
template
<typename date_type, typename weekday_type> date_type next_weekday(const date_type & d, const weekday_type & wd);
Description
Description
Generates a date object representing the date of the following weekday from the given date. If the date given is 2004-May-9 (a Sunday) and the given weekday is Tuesday then the resulting date will be 2004-May-11.
Function template previous_weekday
Function template previous_weekday -- Generates a date object representing the date of the previous weekday from the given date.
boost::date_time::previous_weekday
template
<typename date_type, typename weekday_type> date_type previous_weekday(const date_type & d, const weekday_type & wd);
Description
Description
Generates a date object representing the date of the previous weekday from the given date. If the date given is 2004-May-9 (a Sunday) and the given weekday is Tuesday then the resulting date will be 2004-May-4.
Header <boost/date_time/date_iterator.hpp>
namespace
boost { namespace date_time { template<typename date_type> class date_itr_base; template<typename offset_functor, typename date_type> class date_itr;

// An iterator over dates with varying resolution (day, week, month, year, etc).
enum
date_resolutions { day, week, months, year, decade, century, NumDateResolutions }; } }
Class template date_itr_base
Class template date_itr_base -- Base date iterator type.
boost::date_time::date_itr_base
template
<typename date_type> class date_itr_base { public: // types typedef date_type::duration_type duration_type; typedef date_type value_type; typedef std::input_iterator_tag iterator_category;

// construct/copy/destruct
date_itr_base
(date_type); ~date_itr_base();

// public member functions
date_itr_base
& operator++() ; date_itr_base & operator--() ; virtual duration_type get_offset(const date_type &) const; virtual duration_type get_neg_offset(const date_type &) const; date_type operator *() ; date_type * operator->() ; bool operator<(const date_type &) ; bool operator<=(const date_type &) ; bool operator>(const date_type &) ; bool operator>=(const date_type &) ; bool operator==(const date_type &) ; bool operator!=(const date_type &) ; };
Description
Description
This class provides the skeleton for the creation of iterators. New and interesting interators can be created by plugging in a new function that derives the next value from the current state. generation of various types of -based information.
Template Parameters
date_type
The date_type is a concrete date_type. The date_type must define a duration_type and a calendar_type.
date_itr_base construct/copy/destruct
date_itr_base
construct/copy/destruct
1.
date_itr_base(date_type d);
2.
~date_itr_base();
date_itr_base public member functions
date_itr_base
public member functions
1.
date_itr_base
& operator++() ;
2.
date_itr_base
& operator--() ;
3.
virtual
duration_type get_offset(const date_type & current) const;
4.
virtual
duration_type get_neg_offset(const date_type & current) const;
5.
date_type operator *() ;
6.
date_type * operator->() ;
7.
bool
operator
<(const date_type & d) ;
8.
bool
operator
<=(const date_type & d) ;
9.
bool
operator
>(const date_type & d) ;
10.
bool
operator
>=(const date_type & d) ;
11.
bool
operator
==(const date_type & d) ;
12.
bool
operator
!=(const date_type & d) ;
Class template date_itr
Class template date_itr -- Overrides the base date iterator providing hook for functors.
boost::date_time::date_itr
template
<typename offset_functor, typename date_type> class date_itr : public boost::date_time::date_itr_base< date_type > { public: // types typedef date_type::duration_type duration_type;

// construct/copy/destruct
date_itr
(date_type, int = 1);

// public member functions
// private member functions
virtual
duration_type get_offset(const date_type &) const; virtual duration_type get_neg_offset(const date_type &) const; };
Description
Description
date_itr construct/copy/destruct
date_itr
construct/copy/destruct
1.
date_itr(date_type d, int factor = 1);
date_itr public member functions
date_itr
public member functions
date_itr private member functions
date_itr
private member functions
1.
virtual
duration_type get_offset(const date_type & current) const;
2.
virtual
duration_type get_neg_offset(const date_type & current) const;
Header <boost/date_time/date_names_put.hpp>
namespace
boost { namespace date_time { template<typename Config, typename charT = char, typename OutputIterator = std::ostreambuf_iterator<charT> > class date_names_put; template<typename Config, typename charT = char, typename OutputIterator = std::ostreambuf_iterator<charT> > class all_date_names_put; } }
Class template date_names_put
Class template date_names_put -- Output facet base class for gregorian dates.
boost::date_time::date_names_put
template
<typename Config, typename charT = char, typename OutputIterator = std::ostreambuf_iterator<charT> > class date_names_put { public: // types typedef OutputIterator iter_type; typedef Config::month_type month_type; typedef Config::month_enum month_enum; typedef Config::weekday_enum weekday_enum; typedef Config::special_value_enum special_value_enum; typedef std::basic_string< charT > string_type;

// construct/copy/destruct
date_names_put
();

// public member functions
void
put_special_value
(iter_type &, special_value_enum) const; void put_month_short(iter_type &, month_enum) const; void put_month_long(iter_type &, month_enum) const; void put_weekday_short(iter_type &, weekday_enum) const; void put_weekday_long(iter_type &, weekday_enum) const; bool has_date_sep_chars() const; void year_sep_char(iter_type &) const; void month_sep_char(iter_type &) const; void day_sep_char(iter_type &) const; ymd_order_spec date_order() const; month_format_spec month_format() const;

// protected member functions
virtual
void
do_put_month_short
(iter_type &, month_enum) const; virtual void do_put_month_long(iter_type &, month_enum) const; virtual void do_put_special_value(iter_type &, special_value_enum) const; virtual void do_put_weekday_short(iter_type &, weekday_enum) const; virtual void do_put_weekday_long(iter_type &, weekday_enum) const; virtual bool do_has_date_sep_chars() const; virtual void do_year_sep_char(iter_type &) const; virtual void do_month_sep_char(iter_type &) const; virtual void do_day_sep_char(iter_type &) const; virtual ymd_order_spec do_date_order() const; virtual month_format_spec do_month_format() const; void put_string(iter_type &, const charT *const) const; void put_string(iter_type &, const string_type &) const;

static
std::locale::id id; };
Description
Description
This class is a base class for date facets used to localize the names of months and the names of days in the week.
Requirements of Config•define an enumeration month_enum that enumerates the months. The enumeration should be '1' based eg: Jan==1•define as_short_string and as_long_string
(see langer & kreft p334).
date_names_put construct/copy/destruct
date_names_put
construct/copy/destruct
1.
date_names_put();
date_names_put public member functions
date_names_put
public member functions
1.
void
put_special_value(iter_type & oitr, special_value_enum sv) const;
2.
void
put_month_short(iter_type & oitr, month_enum moy) const;
3.
void
put_month_long(iter_type & oitr, month_enum moy) const;
4.
void
put_weekday_short(iter_type & oitr, weekday_enum wd) const;
5.
void
put_weekday_long(iter_type & oitr, weekday_enum wd) const;
6.
bool
has_date_sep_chars() const;
7.
void
year_sep_char(iter_type & oitr) const;
8.
void
month_sep_char(iter_type & oitr) const;
char between year-month
9.
void
day_sep_char(iter_type & oitr) const;
Char to separate month-day.
10.
ymd_order_spec date_order() const;
Determines the order to put the date elements.
11.
month_format_spec month_format() const;
Determines if month is displayed as integer, short or long string.
date_names_put protected member functions
date_names_put
protected member functions
1.
virtual
void
do_put_month_short(iter_type & oitr, month_enum moy) const;
Default facet implementation uses month_type defaults.
2.
virtual
void
do_put_month_long(iter_type & oitr, month_enum moy) const;
Default facet implementation uses month_type defaults.
3.
virtual
void
do_put_special_value(iter_type & oitr, special_value_enum sv) const;
Default facet implementation for special value types.
4.
virtual
void
do_put_weekday_short(iter_type & , weekday_enum ) const;
5.
virtual
void
do_put_weekday_long(iter_type & , weekday_enum ) const;
6.
virtual
bool
do_has_date_sep_chars() const;
7.
virtual
void
do_year_sep_char(iter_type & oitr) const;
8.
virtual
void
do_month_sep_char(iter_type & oitr) const;
char between year-month
9.
virtual
void
do_day_sep_char(iter_type & oitr) const;
Char to separate month-day.
10.
virtual
ymd_order_spec do_date_order() const;
Default for date order.
11.
virtual
month_format_spec do_month_format() const;
Default month format.
12.
void
put_string(iter_type & oi, const charT *const s) const;
13.
void
put_string(iter_type & oi, const string_type & s1) const;
Class template all_date_names_put
Class template all_date_names_put -- An date name output facet that takes an array of char* to define strings.
boost::date_time::all_date_names_put
template
<typename Config, typename charT = char, typename OutputIterator = std::ostreambuf_iterator<charT> > class all_date_names_put : public boost::date_time::date_names_put< Config, charT, OutputIterator > { public: // types typedef OutputIterator iter_type; typedef Config::month_enum month_enum; typedef Config::weekday_enum weekday_enum; typedef Config::special_value_enum special_value_enum;

// construct/copy/destruct
all_date_names_put
(const charT *const, const charT *const, const charT *const, const charT *const, const charT *const, charT = '-', ymd_order_spec = ymd_order_iso, month_format_spec = month_as_short_string);

// public member functions
const
charT *const * get_short_month_names() const; const charT *const * get_long_month_names() const; const charT *const * get_special_value_names() const; const charT *const * get_short_weekday_names() const; const charT *const * get_long_weekday_names() const;

// protected member functions
virtual
void
do_put_month_short
(iter_type &, month_enum) const; virtual void do_put_month_long(iter_type &, month_enum) const; virtual void do_put_special_value(iter_type &, special_value_enum) const; virtual void do_put_weekday_short(iter_type &, weekday_enum) const; virtual void do_put_weekday_long(iter_type &, weekday_enum) const; virtual void do_month_sep_char(iter_type &) const; virtual void do_day_sep_char(iter_type &) const; virtual ymd_order_spec do_date_order() const; virtual month_format_spec do_month_format() const; };
Description
Description
all_date_names_put construct/copy/destruct
all_date_names_put
construct/copy/destruct
1.
all_date_names_put(const charT *const month_short_names, const charT *const month_long_names, const charT *const special_value_names, const charT *const weekday_short_names, const charT *const weekday_long_names, charT separator_char = '-', ymd_order_spec order_spec = ymd_order_iso, month_format_spec month_format = month_as_short_string);
all_date_names_put public member functions
all_date_names_put
public member functions
1.
const
charT *const * get_short_month_names() const;
2.
const
charT *const * get_long_month_names() const;
3.
const
charT *const * get_special_value_names() const;
4.
const
charT *const * get_short_weekday_names() const;
5.
const
charT *const * get_long_weekday_names() const;
all_date_names_put protected member functions
all_date_names_put
protected member functions
1.
virtual
void
do_put_month_short(iter_type & oitr, month_enum moy) const;
Generic facet that takes array of chars.
2.
virtual
void
do_put_month_long(iter_type & oitr, month_enum moy) const;
Long month names.
3.
virtual
void
do_put_special_value(iter_type & oitr, special_value_enum sv) const;
Special values names.
4.
virtual
void
do_put_weekday_short(iter_type & oitr, weekday_enum wd) const;
5.
virtual
void
do_put_weekday_long(iter_type & oitr, weekday_enum wd) const;
6.
virtual
void
do_month_sep_char(iter_type & oitr) const;
char between year-month
7.
virtual
void
do_day_sep_char(iter_type & oitr) const;
Char to separate month-day.
8.
virtual
ymd_order_spec do_date_order() const;
Set the date ordering.
9.
virtual
month_format_spec do_month_format() const;
Set the date ordering.
Header <boost/date_time/dst_rules.hpp>
Contains template class to provide static dst rule calculations
namespace
boost { namespace date_time { template<typename date_type_, typename time_duration_type_> class dst_calculator; template<typename date_type, typename time_duration_type, typename dst_traits> class dst_calc_engine; template<typename date_type_, typename time_duration_type_, unsigned int dst_start_offset_minutes = , short dst_length_minutes = > class us_dst_rules; template<typename date_type_, typename time_duration_type_> class null_dst_rules;

enum
time_is_dst_result { is_not_in_dst, is_in_dst, ambiguous, invalid_time_label }; } }
Class template dst_calculator
Class template dst_calculator -- Dynamic class used to caluclate dst transition information.
boost::date_time::dst_calculator
template
<typename date_type_, typename time_duration_type_> class dst_calculator { public: // types typedef time_duration_type_ time_duration_type; typedef date_type_ date_type;

// public static functions
time_is_dst_result process_local_dst_start_day(const time_duration_type &, unsigned int, long) ; time_is_dst_result process_local_dst_end_day(const time_duration_type &, unsigned int, long) ; time_is_dst_result local_is_dst(const date_type &, const time_duration_type &, const date_type &, unsigned int, const date_type &, unsigned int, long) ; };
Description
Description
dst_calculator public static functions
dst_calculator
public static functions
1.
time_is_dst_result process_local_dst_start_day(const time_duration_type & time_of_day, unsigned int dst_start_offset_minutes, long dst_length_minutes) ;
Check the local time offset when on dst start day.
On this dst transition, the time label between the transition boundary and the boudary + the offset are invalid times. If before the boundary then still not in dst.

Parameters
dst_length_minutes
Number of minutes to adjust clock forward
dst_start_offset_minutes
Local day offset for start of dst
time_of_day
Time offset in the day for the local time
2.
time_is_dst_result process_local_dst_end_day(const time_duration_type & time_of_day, unsigned int dst_end_offset_minutes, long dst_length_minutes) ;
Check the local time offset when on the last day of dst.
This is the calculation for the DST end day. On that day times prior to the conversion time - dst_length (1 am in US) are still in dst. Times between the above and the switch time are ambiguous. Times after the start_offset are not in dst.

Parameters
dst_end_offset_minutes
Local time of day for end of dst
time_of_day
Time offset in the day for the local time
3.
time_is_dst_result local_is_dst(const date_type & current_day, const time_duration_type & time_of_day, const date_type & dst_start_day, unsigned int dst_start_offset_minutes, const date_type & dst_end_day, unsigned int dst_end_offset_minutes, long dst_length_minutes) ;
Calculates if the given local time is dst or not.
Determines if the time is really in DST or not. Also checks for invalid and ambiguous.

Parameters
current_day
The day to check for dst
dst_end_day
Ending day of dst for the given locality
dst_end_offset_minutes
Offset within day given in dst for dst boundary (eg 120 for US which is 02:00:00)
dst_length_minutes
Length of dst adjusment (eg: 60 for US)
dst_start_day
Starting day of dst for the given locality
dst_start_offset_minutes
Offset within day for dst boundary (eg 120 for US which is 02:00:00)
time_of_day
Time offset within the day to check
Class template dst_calc_engine
Class template dst_calc_engine -- Compile-time configurable daylight savings time calculation engine.
boost::date_time::dst_calc_engine
template
<typename date_type, typename time_duration_type, typename dst_traits> class dst_calc_engine { public: // types typedef date_type::year_type year_type; typedef date_type::calendar_type calendar_type; typedef dst_calculator< date_type, time_duration_type > dstcalc;

// public static functions
time_is_dst_result local_is_dst(const date_type &, const time_duration_type &) ; bool is_dst_boundary_day(date_type) ; time_duration_type dst_offset() ; date_type local_dst_start_day(year_type) ; date_type local_dst_end_day(year_type) ; };
Description
Description
dst_calc_engine public static functions
dst_calc_engine
public static functions
1.
time_is_dst_result local_is_dst(const date_type & d, const time_duration_type & td) ;
Calculates if the given local time is dst or not.
Determines if the time is really in DST or not. Also checks for invalid and ambiguous.
2.
bool
is_dst_boundary_day(date_type d) ;
3.
time_duration_type dst_offset() ;
The time of day for the dst transition (eg: typically 01:00:00 or 02:00:00).
4.
date_type local_dst_start_day(year_type year) ;
5.
date_type local_dst_end_day(year_type year) ;
Class template us_dst_rules
Class template us_dst_rules -- Depricated: Class to calculate dst boundaries for US time zones.
boost::date_time::us_dst_rules
template
<typename date_type_, typename time_duration_type_, unsigned int dst_start_offset_minutes = , short dst_length_minutes = > class us_dst_rules { public: // types typedef time_duration_type_ time_duration_type; typedef date_type_ date_type; typedef date_type::year_type year_type; typedef date_type::calendar_type calendar_type; typedef date_time::last_kday_of_month< date_type > lkday; typedef date_time::first_kday_of_month< date_type > fkday; typedef dst_calculator< date_type, time_duration_type > dstcalc;

// public static functions
time_is_dst_result local_is_dst(const date_type &, const time_duration_type &) ; bool is_dst_boundary_day(date_type) ; date_type local_dst_start_day(year_type) ; date_type local_dst_end_day(year_type) ; time_duration_type dst_offset() ; };
Description
Description
us_dst_rules public static functions
us_dst_rules
public static functions
1.
time_is_dst_result local_is_dst(const date_type & d, const time_duration_type & td) ;
Calculates if the given local time is dst or not.
Determines if the time is really in DST or not. Also checks for invalid and ambiguous.
2.
bool
is_dst_boundary_day(date_type d) ;
3.
date_type local_dst_start_day(year_type year) ;
4.
date_type local_dst_end_day(year_type year) ;
5.
time_duration_type dst_offset() ;
Class template null_dst_rules
Class template null_dst_rules -- Used for local time adjustments in places that don't use dst.
boost::date_time::null_dst_rules
template
<typename date_type_, typename time_duration_type_> class null_dst_rules { public: // types typedef time_duration_type_ time_duration_type; typedef date_type_ date_type;

// public static functions
time_is_dst_result local_is_dst(const date_type &, const time_duration_type &) ; time_is_dst_result utc_is_dst(const date_type &, const time_duration_type &) ; bool is_dst_boundary_day(date_type) ; time_duration_type dst_offset() ; };
Description
Description
null_dst_rules public static functions
null_dst_rules
public static functions
1.
time_is_dst_result local_is_dst(const date_type & , const time_duration_type & ) ;
Calculates if the given local time is dst or not.
2.
time_is_dst_result utc_is_dst(const date_type & , const time_duration_type & ) ;
Calculates if the given utc time is in dst.
3.
bool
is_dst_boundary_day(date_type d) ;
4.
time_duration_type dst_offset() ;
Header <boost/date_time/dst_transition_generators.hpp>
namespace
boost { namespace date_time { template<typename date_type> class dst_day_calc_rule; template<typename spec> class day_calc_dst_rule; } }
Class template dst_day_calc_rule
Class template dst_day_calc_rule -- Defines base interface for calculating start and end date of daylight savings.
boost::date_time::dst_day_calc_rule
template
<typename date_type> class dst_day_calc_rule { public: // types typedef date_type::year_type year_type;

// construct/copy/destruct
~dst_day_calc_rule
();

// public member functions
virtual
date_type start_day(year_type) const; virtual date_type end_day(year_type) const; };
Description
Description
dst_day_calc_rule construct/copy/destruct
dst_day_calc_rule
construct/copy/destruct
1.
~dst_day_calc_rule();
dst_day_calc_rule public member functions
dst_day_calc_rule
public member functions
1.
virtual
date_type start_day(year_type y) const;
2.
virtual
date_type end_day(year_type y) const;
Class template day_calc_dst_rule
Class template day_calc_dst_rule -- Canonical form for a class that provides day rule calculation.
boost::date_time::day_calc_dst_rule
template
<typename spec> class day_calc_dst_rule : : public boost::date_time::dst_day_calc_rule< spec::date_type > { public: // types typedef spec::date_type date_type; typedef date_type::year_type year_type; typedef spec::start_rule start_rule; typedef spec::end_rule end_rule;

// construct/copy/destruct
day_calc_dst_rule
(start_rule, end_rule);

// public member functions
virtual
date_type start_day(year_type) const; virtual date_type end_day(year_type) const; };
Description
Description
This class is used to generate specific sets of dst rules
day_calc_dst_rule construct/copy/destruct
day_calc_dst_rule
construct/copy/destruct
1.
day_calc_dst_rule(start_rule dst_start, end_rule dst_end);
day_calc_dst_rule public member functions
day_calc_dst_rule
public member functions
1.
virtual
date_type start_day(year_type y) const;
2.
virtual
date_type end_day(year_type y) const;
Header <boost/date_time/filetime_functions.hpp>
Function(s) for converting between a FILETIME structure and a time object. This file is only available on systems that have BOOST_HAS_FTIME defined.
namespace
boost { namespace date_time { template<typename time_type> time_type time_from_ftime(const FILETIME &); } }
Function template time_from_ftime
Function template time_from_ftime -- Create a time object from an initialized FILETIME struct.
boost::date_time::time_from_ftime
template
<typename time_type> time_type time_from_ftime(const FILETIME & ft);
Description
Description
Create a time object from an initialized FILETIME struct. A FILETIME struct holds 100-nanosecond units (0.0000001). When built with microsecond resolution the FILETIME's sub second value will be truncated. Nanosecond resolution has no truncation.
Header <boost/date_time/gregorian_calendar.hpp>
namespace
boost { namespace date_time { template<typename ymd_type_, typename date_int_type_> class gregorian_calendar_base; } }
Class template gregorian_calendar_base
Class template gregorian_calendar_base -- An implementation of the Gregorian calendar.
boost::date_time::gregorian_calendar_base
template
<typename ymd_type_, typename date_int_type_> class gregorian_calendar_base { public: // types typedef ymd_type_ ymd_type; // define a type a date split into components typedef ymd_type::month_type month_type; // define a type for representing months typedef ymd_type::day_type day_type; // define a type for representing days typedef ymd_type::year_type year_type; // Type to hold a stand alone year value (eg: 2002). typedef date_int_type_ date_int_type; // Define the integer type to use for internal calculations.

// public static functions
unsigned
short
day_of_week
(const ymd_type &) ; int week_number(const ymd_type &) ; date_int_type day_number(const ymd_type &) ; date_int_type julian_day_number(const ymd_type &) ; long modjulian_day_number(const ymd_type &) ; ymd_type from_day_number(date_int_type) ; ymd_type from_julian_day_number(date_int_type) ; ymd_type from_modjulian_day_number(long) ; bool is_leap_year(year_type) ; unsigned short end_of_month_day(year_type, month_type) ; ymd_type epoch() ; unsigned short days_in_week() ; };
Description
Description
This is a parameterized implementation of a proleptic Gregorian Calendar that can be used in the creation of date systems or just to perform calculations. All the methods of this class are static functions, so the intent is to never create instances of this class.
gregorian_calendar_base public static functions
gregorian_calendar_base
public static functions
1.
unsigned
short
day_of_week(const ymd_type & ymd) ;
2.
int
week_number(const ymd_type & ymd) ;
3.
date_int_type day_number(const ymd_type & ymd) ;
4.
date_int_type julian_day_number(const ymd_type & ymd) ;
5.
long
modjulian_day_number(const ymd_type & ymd) ;
6.
ymd_type from_day_number(date_int_type ) ;
7.
ymd_type from_julian_day_number(date_int_type ) ;
8.
ymd_type from_modjulian_day_number(long ) ;
9.
bool
is_leap_year(year_type ) ;
10.
unsigned
short
end_of_month_day(year_type y, month_type m) ;
11.
ymd_type epoch() ;
12.
unsigned
short
days_in_week() ;
Header <boost/date_time/int_adapter.hpp>
namespace
boost { namespace date_time { template<typename int_type_> class int_adapter; template<typename charT, typename traits, typename int_type> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > &, const int_adapter< int_type > &); } }
Class template int_adapter
Class template int_adapter -- Adapter to create integer types with +-infinity, and not a value.
boost::date_time::int_adapter
template
<typename int_type_> class int_adapter { public: // types typedef int_type_ int_type;

// construct/copy/destruct
int_adapter
(int_type);

// public member functions
bool
is_infinity
() const; bool is_pos_infinity() const; bool is_neg_infinity() const; bool is_nan() const; bool is_special() const; bool operator==(const int_adapter &) const; bool operator==(const int &) const; bool operator!=(const int_adapter &) const; bool operator!=(const int &) const; bool operator<(const int_adapter &) const; bool operator<(const int &) const; bool operator>(const int_adapter &) const; int_type as_number() const; special_values as_special() const; template<typename rhs_type> int_adapter operator+(const int_adapter< rhs_type > &) const; int_adapter operator+(const int_type) const; template<typename rhs_type> int_adapter operator-(const int_adapter< rhs_type > &) const; int_adapter operator-(const int_type) const; int_adapter operator *(const int_adapter &) const; int_adapter operator *(const int) const; int_adapter operator/(const int_adapter &) const; int_adapter operator/(const int) const; int_adapter operator%(const int_adapter &) const; int_adapter operator%(const int) const;

// public static functions
bool
has_infinity
() ; const int_adapter pos_infinity() ; const int_adapter neg_infinity() ; const int_adapter not_a_number() ; int_adapter max BOOST_PREVENT_MACRO_SUBSTITUTION() ; int_adapter min BOOST_PREVENT_MACRO_SUBSTITUTION() ; int_adapter from_special(special_values) ; bool is_inf(int_type) ; bool is_neg_inf(int_type) ; bool is_pos_inf(int_type) ; bool is_not_a_number(int_type) ; special_values to_special(int_type) ; int_type maxcount() ;

// private member functions
int
compare
(const int_adapter &) const; int_adapter mult_div_specials(const int_adapter &) const; int_adapter mult_div_specials(const int &) const; };
Description
Description
This class is used internally in counted date/time representations. It adds the floating point like features of infinities and not a number. It also provides mathmatical operations with consideration to special values following these rules: +infinity - infinity == Not A Number (NAN) infinity * non-zero == infinity infinity * zero == NAN +infinity * -integer == -infinity infinity / infinity == NAN infinity * infinity == infinity *
int_adapter construct/copy/destruct
int_adapter
construct/copy/destruct
1.
int_adapter(int_type v);
int_adapter public member functions
int_adapter
public member functions
1.
bool
is_infinity() const;
2.
bool
is_pos_infinity() const;
3.
bool
is_neg_infinity() const;
4.
bool
is_nan() const;
5.
bool
is_special() const;
6.
bool
operator
==(const int_adapter & rhs) const;
7.
bool
operator
==(const int & rhs) const;
8.
bool
operator
!=(const int_adapter & rhs) const;
9.
bool
operator
!=(const int & rhs) const;
10.
bool
operator
<(const int_adapter & rhs) const;
11.
bool
operator
<(const int & rhs) const;
12.
bool
operator
>(const int_adapter & rhs) const;
13.
int_type as_number() const;
14.
special_values as_special() const;
Returns either special value type or is_not_special.
15.
template
<typename rhs_type> int_adapter operator+(const int_adapter< rhs_type > & rhs) const;
Operator allows for adding dissimilar int_adapter types. The return type will match that of the the calling object's type
16.
int_adapter
operator
+(const int_type rhs) const;
17.
template
<typename rhs_type> int_adapter operator-(const int_adapter< rhs_type > & rhs) const;
Operator allows for subtracting dissimilar int_adapter types. The return type will match that of the the calling object's type
18.
int_adapter
operator
-(const int_type rhs) const;
19.
int_adapter
operator
*(const int_adapter & rhs) const;
20.
int_adapter
operator
*(const int rhs) const;
Provided for cases when automatic conversion from 'int' to 'int_adapter' causes incorrect results.
21.
int_adapter
operator
/(const int_adapter & rhs) const;
22.
int_adapter
operator
/(const int rhs) const;
Provided for cases when automatic conversion from 'int' to 'int_adapter' causes incorrect results.
23.
int_adapter
operator
%(const int_adapter & rhs) const;
24.
int_adapter
operator
%(const int rhs) const;
Provided for cases when automatic conversion from 'int' to 'int_adapter' causes incorrect results.
int_adapter public static functions
int_adapter
public static functions
1.
bool
has_infinity() ;
2.
const
int_adapter
pos_infinity() ;
3.
const
int_adapter
neg_infinity() ;
4.
const
int_adapter
not_a_number() ;
5.
int_adapter
max BOOST_PREVENT_MACRO_SUBSTITUTION() ;
6.
int_adapter
min BOOST_PREVENT_MACRO_SUBSTITUTION() ;
7.
int_adapter
from_special(special_values sv) ;
8.
bool
is_inf(int_type v) ;
9.
bool
is_neg_inf(int_type v) ;
10.
bool
is_pos_inf(int_type v) ;
11.
bool
is_not_a_number(int_type v) ;
12.
special_values to_special(int_type v) ;
Returns either special value type or is_not_special.
13.
int_type maxcount() ;
int_adapter private member functions
int_adapter
private member functions
1.
int
compare(const int_adapter & rhs) const;
returns -1, 0, 1, or 2 if 'this' is <, ==, >, or 'nan comparison' rhs
2.
int_adapter
mult_div_specials(const int_adapter & rhs) const;
Assumes at least 'this' or 'rhs' is a special value.
3.
int_adapter
mult_div_specials(const int & rhs) const;
Assumes 'this' is a special value.
Function template operator<<
Function template operator<< --
boost::date_time::operator<<
template
<typename charT, typename traits, typename int_type> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const int_adapter< int_type > & ia);
Description
Description
Expected output is either a numeric representation or a special values representation. Ex. "12", "+infinity", "not-a-number", etc.
Header <boost/date_time/iso_format.hpp>
namespace
boost { namespace date_time { template<typename charT> class iso_format_base;

template
<> class iso_format_base<wchar_t>;

template
<typename charT> class iso_format; template<typename charT> class iso_extended_format; } }
Class template iso_format_base
Class template iso_format_base -- Class to provide common iso formatting spec.
boost::date_time::iso_format_base
template
<typename charT> class iso_format_base { public:

// public static functions
month_format_spec month_format() ; const charT * not_a_date() ; const charT * pos_infinity() ; const charT * neg_infinity() ; charT year_sep_char() ; charT month_sep_char() ; charT day_sep_char() ; charT hour_sep_char() ; charT minute_sep_char() ; charT second_sep_char() ; charT period_start_char() ; charT time_start_char() ; charT week_start_char() ; charT period_sep_char() ; charT time_sep_char() ; charT fractional_time_sep_char() ; bool is_component_sep(charT) ; bool is_fractional_time_sep(charT) ; bool is_timezone_sep(charT) ; charT element_sep_char() ; };
Description
Description
iso_format_base public static functions
iso_format_base
public static functions
1.
month_format_spec month_format() ;
Describe month format -- its an integer in iso format.
2.
const
charT * not_a_date() ;
String used printed is date is invalid.
3.
const
charT * pos_infinity() ;
String used to for positive infinity value.
4.
const
charT * neg_infinity() ;
String used to for positive infinity value.
5.
charT year_sep_char() ;
ISO char for a year -- used in durations.
6.
charT month_sep_char() ;
ISO char for a month.
7.
charT day_sep_char() ;
ISO char for a day.
8.
charT hour_sep_char() ;
char for minute
9.
charT minute_sep_char() ;
char for minute
10.
charT second_sep_char() ;
char for second
11.
charT period_start_char() ;
ISO char for a period.
12.
charT time_start_char() ;
Used in time in mixed strings to set start of time.
13.
charT week_start_char() ;
Used in mixed strings to identify start of a week number.
14.
charT period_sep_char() ;
Separators for periods.
15.
charT time_sep_char() ;
Separator for hh:mm:ss.
16.
charT fractional_time_sep_char() ;
Preferred Separator for hh:mm:ss,decimal_fraction.
17.
bool
is_component_sep(charT sep) ;
18.
bool
is_fractional_time_sep(charT sep) ;
19.
bool
is_timezone_sep(charT sep) ;
20.
charT element_sep_char() ;
Specializations
Specializations
•
Class iso_format_base<wchar_t>
Class iso_format_base<wchar_t>
Class iso_format_base<wchar_t> -- Class to provide common iso formatting spec.
boost::date_time::iso_format_base<wchar_t>
class
iso_format_base<wchar_t> { public:

// public static functions
month_format_spec month_format() ; const wchar_t * not_a_date() ; const wchar_t * pos_infinity() ; const wchar_t * neg_infinity() ; wchar_t year_sep_char() ; wchar_t month_sep_char() ; wchar_t day_sep_char() ; wchar_t hour_sep_char() ; wchar_t minute_sep_char() ; wchar_t second_sep_char() ; wchar_t period_start_char() ; wchar_t time_start_char() ; wchar_t week_start_char() ; wchar_t period_sep_char() ; wchar_t time_sep_char() ; wchar_t fractional_time_sep_char() ; bool is_component_sep(wchar_t) ; bool is_fractional_time_sep(wchar_t) ; bool is_timezone_sep(wchar_t) ; wchar_t element_sep_char() ; };
Description
Description
iso_format_base public static functions
iso_format_base
public static functions
1.
month_format_spec month_format() ;
Describe month format -- its an integer in iso format.
2.
const
wchar_t
* not_a_date() ;
String used printed is date is invalid.
3.
const
wchar_t
* pos_infinity() ;
String used to for positive infinity value.
4.
const
wchar_t
* neg_infinity() ;
String used to for positive infinity value.
5.
wchar_t
year_sep_char() ;
ISO char for a year -- used in durations.
6.
wchar_t
month_sep_char() ;
ISO char for a month.
7.
wchar_t
day_sep_char() ;
ISO char for a day.
8.
wchar_t
hour_sep_char() ;
char for minute
9.
wchar_t
minute_sep_char() ;
char for minute
10.
wchar_t
second_sep_char() ;
char for second
11.
wchar_t
period_start_char() ;
ISO char for a period.
12.
wchar_t
time_start_char() ;
Used in time in mixed strings to set start of time.
13.
wchar_t
week_start_char() ;
Used in mixed strings to identify start of a week number.
14.
wchar_t
period_sep_char() ;
Separators for periods.
15.
wchar_t
time_sep_char() ;
Separator for hh:mm:ss.
16.
wchar_t
fractional_time_sep_char() ;
Preferred Separator for hh:mm:ss,decimal_fraction.
17.
bool
is_component_sep(wchar_t sep) ;
18.
bool
is_fractional_time_sep(wchar_t sep) ;
19.
bool
is_timezone_sep(wchar_t sep) ;
20.
wchar_t
element_sep_char() ;
Class template iso_format
Class template iso_format -- Format description for iso normal YYYYMMDD.
boost::date_time::iso_format
template
<typename charT> class iso_format : public boost::date_time::iso_format_base< charT > { public:

// public static functions
bool
has_date_sep_chars
() ; };
Description
Description
iso_format public static functions
iso_format
public static functions
1.
bool
has_date_sep_chars() ;
The ios standard format doesn't use char separators.
Class template iso_extended_format
Class template iso_extended_format -- Extended format uses seperators YYYY-MM-DD.
boost::date_time::iso_extended_format
template
<typename charT> class iso_extended_format : : public boost::date_time::iso_format_base< charT > { public:

// public static functions
bool
has_date_sep_chars
() ; };
Description
Description
iso_extended_format public static functions
iso_extended_format
public static functions
1.
bool
has_date_sep_chars() ;
Extended format needs char separators.
Header <boost/date_time/local_time_adjustor.hpp>
Time adjustment calculations for local times
namespace
boost { namespace date_time { template<typename time_duration_type, short hours, unsigned short minutes = > class utc_adjustment; template<typename time_type, typename dst_rules> class dynamic_local_time_adjustor; template<typename time_type, typename dst_rules, typename utc_offset_rules> class static_local_time_adjustor; template<typename time_type, short utc_offset, typename dst_rule> class local_adjustor; void dummy_to_prevent_msvc6_ice(); } }
Class template utc_adjustment
Class template utc_adjustment -- Provides a base offset adjustment from utc.
boost::date_time::utc_adjustment
template
<typename time_duration_type, short hours, unsigned short minutes = > class utc_adjustment { public:

// public static functions
time_duration_type local_to_utc_base_offset() ; time_duration_type utc_to_local_base_offset() ; };
Description
Description
utc_adjustment public static functions
utc_adjustment
public static functions
1.
time_duration_type local_to_utc_base_offset() ;
2.
time_duration_type utc_to_local_base_offset() ;
Class template dynamic_local_time_adjustor
Class template dynamic_local_time_adjustor -- Allow sliding utc adjustment with fixed dst rules.
boost::date_time::dynamic_local_time_adjustor
template
<typename time_type, typename dst_rules> class dynamic_local_time_adjustor { public: // types typedef time_type::time_duration_type time_duration_type; typedef time_type::date_type date_type;

// construct/copy/destruct
dynamic_local_time_adjustor
(time_duration_type);

// public member functions
time_duration_type utc_offset(bool) ; };
Description
Description
dynamic_local_time_adjustor construct/copy/destruct
dynamic_local_time_adjustor
construct/copy/destruct
1.
dynamic_local_time_adjustor(time_duration_type utc_offset);
dynamic_local_time_adjustor public member functions
dynamic_local_time_adjustor
public member functions
1.
time_duration_type utc_offset(bool is_dst) ;
Presumes local time.
Class template static_local_time_adjustor
Class template static_local_time_adjustor -- Embed the rules for local time adjustments at compile time.
boost::date_time::static_local_time_adjustor
template
<typename time_type, typename dst_rules, typename utc_offset_rules> class static_local_time_adjustor { public: // types typedef time_type::time_duration_type time_duration_type; typedef time_type::date_type date_type;

// public static functions
time_duration_type utc_to_local_offset(const time_type &) ; time_duration_type local_to_utc_offset(const time_type &, date_time::dst_flags = date_time::calculate) ; };
Description
Description
static_local_time_adjustor public static functions
static_local_time_adjustor
public static functions
1.
time_duration_type utc_to_local_offset(const time_type & t) ;
Calculates the offset from a utc time to local based on dst and utc offset.
The logic is as follows. Starting with UTC time use the offset to create a label for an non-dst adjusted local time. Then call dst_rules::local_is_dst with the non adjust local time. The results of this function will either unabiguously decide that the initial local time is in dst or return an illegal or ambiguous result. An illegal result only occurs at the end of dst (where labels are skipped) and indicates that dst has ended. An ambiguous result means that we need to recheck by making a dst adjustment and then rechecking. If the dst offset is added to the utc time and the recheck proves non-ambiguous then we are past the boundary. If it is still ambiguous then we are ahead of the boundary and dst is still in effect.
TODO -- check if all dst offsets are positive. If not then the algorithm needs to check for this and reverse the illegal/ambiguous logic.
Parameters
t
UTC time to calculate offset to local time This adjustment depends on the following observations about the workings of the DST boundary offset. Since UTC time labels are monotonically increasing we can determine if a given local time is in DST or not and therefore adjust the offset appropriately.
2.
time_duration_type local_to_utc_offset(const time_type & t, date_time::dst_flags dst = date_time::calculate) ;
Get the offset to UTC given a local time.
Class template local_adjustor
Class template local_adjustor -- Template that simplifies the creation of local time calculator.
boost::date_time::local_adjustor
template
<typename time_type, short utc_offset, typename dst_rule> class local_adjustor { public: // types typedef time_type::time_duration_type time_duration_type; typedef time_type::date_type date_type; typedef static_local_time_adjustor< time_type, dst_rule, utc_adjustment< time_duration_type, utc_offset > > dst_adjustor;

// public static functions
time_type utc_to_local(const time_type &) ; time_type local_to_utc(const time_type &, date_time::dst_flags = date_time::calculate) ; };
Description
Description
Use this template to create the timezone to utc convertors as required.
This class will also work for other regions that don't use dst and have a utc offset which is an integral number of hours.
Template Parameters
-time_type -- Time class to use -utc_offset -- Number hours local time is adjust from utc -use_dst -- true (default) if region uses dst, false otherwise For example: //eastern timezone is utc-5 typedef date_time::local_adjustor<ptime, -5, us_dst> us_eastern; typedef date_time::local_adjustor<ptime, -6, us_dst> us_central; typedef date_time::local_adjustor<ptime, -7, us_dst> us_mountain; typedef date_time::local_adjustor<ptime, -8, us_dst> us_pacific; typedef date_time::local_adjustor<ptime, -7, no_dst> us_arizona;
local_adjustor public static functions
local_adjustor
public static functions
1.
time_type utc_to_local(const time_type & t) ;
Convert a utc time to local time.
2.
time_type local_to_utc(const time_type & t, date_time::dst_flags dst = date_time::calculate) ;
Convert a local time to utc.
Header <boost/date_time/local_timezone_defs.hpp>
namespace
boost { namespace date_time { template<typename date_type> struct us_dst_trait; template<typename date_type> struct eu_dst_trait; template<typename date_type> struct uk_dst_trait; template<typename date_type> struct acst_dst_trait; } }
Struct template us_dst_trait
Struct template us_dst_trait -- Specification for daylight savings start rules in US.
boost::date_time::us_dst_trait
template
<typename date_type> struct us_dst_trait { // types typedef date_type::day_of_week_type day_of_week_type; typedef date_type::month_type month_type; typedef date_time::first_kday_of_month< date_type > start_rule_functor; typedef date_time::last_kday_of_month< date_type > end_rule_functor;

// public static functions
day_of_week_type start_day() ; month_type start_month() ; day_of_week_type end_day() ; month_type end_month() ; int dst_start_offset_minutes() ; int dst_end_offset_minutes() ; int dst_shift_length_minutes() ; };
Description
Description
This class is used to configure dst_calc_engine template typically as follows: using namespace boost::gregorian; using namespace boost::posix_time; typedef us_dst_trait<date> us_dst_traits; typedef boost::date_time::dst_calc_engine<date, time_duration, us_dst_traits> us_dst_calc; //calculate the 2002 transition day of USA April 7 2002 date dst_start = us_dst_calc::local_dst_start_day(2002); //calculate the 2002 transition day of USA Oct 27 2002 date dst_end = us_dst_calc::local_dst_end_day(2002); //check if a local time is in dst or not -- posible answers //are yes, no, invalid time label, ambiguous ptime t(...some time...); if (us_dst::local_is_dst(t.date(), t.time_of_day()) == boost::date_time::is_not_in_dst) { } This generates a type suitable for the calculation of dst transitions for the United States. Of course other templates can be used for other locales.
us_dst_trait public static functions
us_dst_trait
public static functions
1.
day_of_week_type start_day() ;
2.
month_type start_month() ;
3.
day_of_week_type end_day() ;
4.
month_type end_month() ;
5.
int
dst_start_offset_minutes() ;
6.
int
dst_end_offset_minutes() ;
7.
int
dst_shift_length_minutes() ;
Struct template eu_dst_trait
Struct template eu_dst_trait -- Rules for daylight savings start in the EU (Last Sun in Mar).
boost::date_time::eu_dst_trait
template
<typename date_type> struct eu_dst_trait { // types typedef date_type::day_of_week_type day_of_week_type; typedef date_type::month_type month_type; typedef date_time::last_kday_of_month< date_type > start_rule_functor; typedef date_time::last_kday_of_month< date_type > end_rule_functor;

// public static functions
day_of_week_type start_day() ; month_type start_month() ; day_of_week_type end_day() ; month_type end_month() ; int dst_start_offset_minutes() ; int dst_end_offset_minutes() ; int dst_shift_length_minutes() ; };
Description
Description
These amount to the following:•Start of dst day is last Sunday in March•End day of dst is last Sunday in Oct•Going forward switch time is 2:00 am (offset 120 minutes)•Going back switch time is 3:00 am (off set 180 minutes)•Shift duration is one hour (60 minutes)
eu_dst_trait public static functions
eu_dst_trait
public static functions
1.
day_of_week_type start_day() ;
2.
month_type start_month() ;
3.
day_of_week_type end_day() ;
4.
month_type end_month() ;
5.
int
dst_start_offset_minutes() ;
6.
int
dst_end_offset_minutes() ;
7.
int
dst_shift_length_minutes() ;
Struct template uk_dst_trait
Struct template uk_dst_trait -- Alternative dst traits for some parts of the United Kingdom.
boost::date_time::uk_dst_trait
template
<typename date_type> struct uk_dst_trait : public boost::date_time::eu_dst_trait< date_type > {

// public static functions
int
dst_start_offset_minutes
() ; int dst_end_offset_minutes() ; int dst_shift_length_minutes() ; };
Description
Description
uk_dst_trait public static functions
uk_dst_trait
public static functions
1.
int
dst_start_offset_minutes() ;
2.
int
dst_end_offset_minutes() ;
3.
int
dst_shift_length_minutes() ;
Struct template acst_dst_trait
Struct template acst_dst_trait --
boost::date_time::acst_dst_trait
template
<typename date_type> struct acst_dst_trait { // types typedef date_type::day_of_week_type day_of_week_type; typedef date_type::month_type month_type; typedef date_time::last_kday_of_month< date_type > start_rule_functor; typedef date_time::last_kday_of_month< date_type > end_rule_functor;

// public static functions
day_of_week_type start_day() ; month_type start_month() ; day_of_week_type end_day() ; month_type end_month() ; int dst_start_offset_minutes() ; int dst_end_offset_minutes() ; int dst_shift_length_minutes() ; };
Description
Description
acst_dst_trait public static functions
acst_dst_trait
public static functions
1.
day_of_week_type start_day() ;
2.
month_type start_month() ;
3.
day_of_week_type end_day() ;
4.
month_type end_month() ;
5.
int
dst_start_offset_minutes() ;
6.
int
dst_end_offset_minutes() ;
7.
int
dst_shift_length_minutes() ;
Header <boost/date_time/microsec_time_clock.hpp>
This file contains a high resolution time clock implementation.
namespace
boost { namespace date_time { template<typename time_type> class microsec_clock; } }
Class template microsec_clock
Class template microsec_clock -- A clock providing microsecond level resolution.
boost::date_time::microsec_clock
template
<typename time_type> class microsec_clock { public: // types typedef time_type::date_type date_type; typedef time_type::time_duration_type time_duration_type; typedef time_duration_type::rep_type resolution_traits_type;

// public static functions
time_type local_time() ;

// private static functions
time_type create_time(timeval *) ; time_type local_time() ; time_type create_time(FILETIME &) ; };
Description
Description
A high precision clock that measures the local time at a resolution up to microseconds and adjusts to the resolution of the time system. For example, for the a library configuration with nano second resolution, the last 3 places of the fractional seconds will always be 000 since there are 1000 nano-seconds in a micro second.
microsec_clock public static functions
microsec_clock
public static functions
1.
time_type local_time() ;
Return the local time based on computer clock settings.
microsec_clock private static functions
microsec_clock
private static functions
1.
time_type create_time(timeval * tv) ;
2.
time_type local_time() ;
Return the local time based on computer clock settings.
3.
time_type create_time(FILETIME & ft) ;
Header <boost/date_time/parse_format_base.hpp>
namespace
boost { namespace date_time {

// Enum for distinguishing parsing and formatting options.
enum
month_format_spec { month_as_integer, month_as_short_string, month_as_long_string }; enum ymd_order_spec; } }
Type ymd_order_spec
Type ymd_order_spec -- Enum for distinguishing the order of Month, Day, & Year.
boost::date_time::ymd_order_spec
enum
ymd_order_spec { ymd_order_iso, ymd_order_dmy, ymd_order_us };
Header <boost/date_time/period.hpp>
This file contain the implementation of the period abstraction. This is basically the same idea as a range. Although this class is intended for use in the time library, it is pretty close to general enough for other numeric uses.
namespace
boost { namespace date_time { template<typename point_rep, typename duration_rep> class period; } }
Class template period
Class template period -- Provides generalized period type useful in date-time systems.
boost::date_time::period
template
<typename point_rep, typename duration_rep> class period { public: // types typedef point_rep point_type; typedef duration_rep duration_type;

// construct/copy/destruct
period
(point_rep, point_rep); period(point_rep, duration_rep);

// public member functions
point_rep begin() const; point_rep end() const; point_rep last() const; duration_rep length() const; bool is_null() const; bool operator==(const period &) const; bool operator<(const period &) const; void shift(const duration_rep &) ; bool contains(const point_rep &) const; bool contains(const period &) const; bool intersects(const period &) const; bool is_adjacent(const period &) const; bool is_before(const point_rep &) const; bool is_after(const point_rep &) const; period intersection(const period &) const; period merge(const period &) const; period span(const period &) const; };
Description
Description
This template uses a class to represent a time point within the period and another class to represent a duration. As a result, this class is not appropriate for use when the number and duration representation are the same (eg: in the regular number domain).
A period can be specified by providing either the starting point and a duration or the starting point and the end point( end is NOT part of the period but 1 unit past it. A period will be "invalid" if either start_point >= end_point or the given duration is < 0. Any valid period will return false for is_null().
Zero length periods are considered valid. In this case the start point is exactly 1 unit less than the end point, in other words start is equal to last.
In the case that the begin and last are the same, the period has a length of zero units. For example, suppose this is a period of days. That is, each time-point represents a single day. If the start and the last is the same day then the period is zero length.
The best way to handle periods is usually to provide a start point and a duration. So, day1 + 7 days is a week period which includes all of the first day and 6 more days (eg: Sun to Sat).
period construct/copy/destruct
period
construct/copy/destruct
1.
period(point_rep first_point, point_rep end_point);
create a period from begin to last eg: [begin,end)
If end <= begin then the period will be invalid
2.
period(point_rep first_point, duration_rep len);
create a period as [begin, begin+len)
If len is < 0 then the period will be invalid
period public member functions
period
public member functions
1.
point_rep begin() const;
Return the first element in the period.
2.
point_rep end() const;
Return one past the last element.
3.
point_rep last() const;
Return the last item in the period.
4.
duration_rep length() const;
Return the length of the period.
5.
bool
is_null() const;
True if period is ill formed (length less than zero).
6.
bool
operator
==(const period & rhs) const;
Equality operator.
7.
bool
operator
<(const period & rhs) const;
Strict as defined by rhs.last <= lhs.last.
8.
void
shift(const duration_rep & d) ;
Shift the start and end by the specified amount.
9.
bool
contains(const point_rep & point) const;
True if the point is inside the period.
10.
bool
contains(const period & other) const;
True if this period fully contains (or equals) the other period.
11.
bool
intersects(const period & other) const;
True if the periods overlap in any way.
12.
bool
is_adjacent(const period & other) const;
True if periods are next to each other without a gap.
13.
bool
is_before(const point_rep & point) const;
True if all of the period is prior to the passed point or end <= t.
14.
bool
is_after(const point_rep & point) const;
True if all of the period is prior or t < start.
15.
period
intersection(const period & other) const;
Returns the period of intersection or invalid range no intersection.
16.
period
merge(const period & other) const;
Returns the union of intersecting periods -- or null period.
17.
period
span(const period & other) const;
Combine two periods with earliest start and latest end.
Combines two periods and any gap between them such that start = min(p1.start, p2.start) end = max(p1.end , p2.end) [---p1---) [---p2---) result: [-----------p3----------) *
Header <boost/date_time/special_defs.hpp>
namespace
boost { namespace date_time {

enum
special_values { not_a_date_time, neg_infin, pos_infin, min_date_time, max_date_time, not_special, NumSpecialValues }; } }
Header <boost/date_time/time.hpp>
This file contains the interface for the time associated classes.
namespace
boost { namespace date_time { template<typename T, typename time_system> class base_time; } }
Class template base_time
Class template base_time -- Representation of a precise moment in time, including the date.
boost::date_time::base_time
template
<typename T, typename time_system> class base_time { public: // types typedef T time_type; typedef time_system::time_rep_type time_rep_type; typedef time_system::date_type date_type; typedef time_system::date_duration_type date_duration_type; typedef time_system::time_duration_type time_duration_type;

// construct/copy/destruct
base_time
(const date_type &, const time_duration_type &, dst_flags = not_dst); base_time(const time_rep_type &);

// public member functions
date_type date() const; time_duration_type time_of_day() const; std::string zone_name() const; bool is_not_a_date_time() const; bool is_infinity() const; bool is_pos_infinity() const; bool is_neg_infinity() const; bool operator==(const time_type &) const; bool operator<(const time_type &) const; time_duration_type operator-(const time_type &) const; time_type operator+(const date_duration_type &) const; time_type operator+=(const date_duration_type &) ; time_type operator-(const date_duration_type &) const; time_type operator-=(const date_duration_type &) ; time_type operator+(const time_duration_type &) const; time_type operator+=(const time_duration_type &) ; time_type operator-(const time_duration_type &) const; time_type operator-=(const time_duration_type &) ; };
Description
Description
This class is a skeleton for the interface of a temporal type with a resolution that is higher than a day. It is intended that this class be the base class and that the actual time class be derived using the BN pattern. In this way, the derived class can make decisions such as 'should there be a default constructor' and what should it set its value to, should there be optional constructors say allowing only an time_durations that generate a time from a clock,etc. So, in fact multiple time types can be created for a time_system with different construction policies, and all of them can perform basic operations by only writing a copy constructor. Finally, compiler errors are also shorter.
The real behavior of the time class is provided by the time_system template parameter. This class must provide all the logic for addition, subtraction, as well as define all the interface types.
base_time construct/copy/destruct
base_time
construct/copy/destruct
1.
base_time(const date_type & day, const time_duration_type & td, dst_flags dst = not_dst);
2.
base_time(const time_rep_type & rhs);
base_time public member functions
base_time
public member functions
1.
date_type date() const;
2.
time_duration_type time_of_day() const;
3.
std::string zone_name() const;
4.
bool
is_not_a_date_time() const;
check to see if date is not a value
5.
bool
is_infinity() const;
check to see if date is one of the infinity values
6.
bool
is_pos_infinity() const;
check to see if date is greater than all possible dates
7.
bool
is_neg_infinity() const;
check to see if date is greater than all possible dates
8.
bool
operator
==(const time_type & rhs) const;
Equality operator -- others generated by boost::equality_comparable.
9.
bool
operator
<(const time_type & rhs) const;
Equality operator -- others generated by boost::less_than_comparable.
10.
time_duration_type operator-(const time_type & rhs) const;
difference between two times
11.
time_type operator+(const date_duration_type & dd) const;
add date durations
12.
time_type operator+=(const date_duration_type & dd) ;
13.
time_type operator-(const date_duration_type & dd) const;
subtract date durations
14.
time_type operator-=(const date_duration_type & dd) ;
15.
time_type operator+(const time_duration_type & td) const;
add time durations
16.
time_type operator+=(const time_duration_type & td) ;
17.
time_type operator-(const time_duration_type & rhs) const;
subtract time durations
18.
time_type operator-=(const time_duration_type & td) ;
Header <boost/date_time/time_clock.hpp>
This file contains the interface for clock devices.
namespace
boost { namespace date_time { template<typename date_type, typename time_type> class second_clock; } }
Class template second_clock
Class template second_clock -- A clock providing time level services based on C time_t capabilities.
boost::date_time::second_clock
template
<typename date_type, typename time_type> class second_clock { public: // types typedef time_type::time_duration_type time_duration_type;

// public static functions
time_type local_time() ; time_type universal_time() ;

// private static functions
time_type create_time(::std::tm *) ; };
Description
Description
This clock provides resolution to the 1 second level
second_clock public static functions
second_clock
public static functions
1.
time_type local_time() ;
2.
time_type universal_time() ;
Get the current day in universal date as a ymd_type.
second_clock private static functions
second_clock
private static functions
1.
time_type create_time(::std::tm * current) ;
Header <boost/date_time/time_defs.hpp>
This file contains nice definitions for handling the resoluion of various time reprsentations.
namespace
boost { namespace date_time {

// Defines some nice types for handling time level resolutions.
enum
time_resolutions { sec, tenth, hundreth, milli, ten_thousandth, micro, nano, NumResolutions };

// Flags for daylight savings or summer time.
enum
dst_flags { not_dst, is_dst, calculate }; } }
Header <boost/date_time/time_duration.hpp>
namespace
boost { namespace date_time { template<typename T, typename rep_type> class time_duration; template<typename base_duration, long frac_of_second> class subsecond_duration; } }
Class template time_duration
Class template time_duration -- Represents some amount of elapsed time measure to a given resolution.
boost::date_time::time_duration
template
<typename T, typename rep_type> class time_duration { public: // types typedef T duration_type; typedef rep_type traits_type; typedef rep_type::day_type day_type; typedef rep_type::hour_type hour_type; typedef rep_type::min_type min_type; typedef rep_type::sec_type sec_type; typedef rep_type::fractional_seconds_type fractional_seconds_type; typedef rep_type::tick_type tick_type; typedef rep_type::impl_type impl_type;

// construct/copy/destruct
time_duration
(); time_duration(hour_type, min_type, sec_type = 0, fractional_seconds_type = 0); time_duration(const time_duration< T, rep_type > &); time_duration(special_values); time_duration(impl_type);

// public member functions
hour_type hours() const; min_type minutes() const; sec_type seconds() const; sec_type total_seconds() const; tick_type total_milliseconds() const; tick_type total_nanoseconds() const; tick_type total_microseconds() const; fractional_seconds_type fractional_seconds() const; duration_type invert_sign() const; bool is_negative() const; bool operator<(const time_duration &) const; bool operator==(const time_duration &) const; duration_type operator-() const; duration_type operator-(const duration_type &) const; duration_type operator+(const duration_type &) const; duration_type operator/(int) ; duration_type operator-=(const duration_type &) ; duration_type operator+=(const duration_type &) ; duration_type operator/=(int) ; duration_type operator *(int) const; duration_type operator *=(int) ; tick_type ticks() const; bool is_special() const; bool is_pos_infinity() const; bool is_neg_infinity() const; bool is_not_a_date_time() const; impl_type get_rep() const;

// public static functions
duration_type unit() ; tick_type ticks_per_second() ; time_resolutions resolution() ; unsigned short num_fractional_digits() ;

// protected member functions
};
Description
Description
This class represents a standard set of capabilities for all counted time durations. Time duration implementations should derive from this class passing their type as the first template parameter. This design allows the subclass duration types to provide custom construction policies or other custom features not provided here.
time_duration construct/copy/destruct
time_duration
construct/copy/destruct
1.
time_duration();
2.
time_duration(hour_type hours, min_type minutes, sec_type seconds = 0, fractional_seconds_type frac_sec = 0);
3.
time_duration(const time_duration< T, rep_type > & other);
Construct from another time_duration (Copy constructor).
4.
time_duration(special_values sv);
Construct from special_values.
5.
time_duration(impl_type in);
time_duration public member functions
time_duration
public member functions
1.
hour_type hours() const;
Returns number of hours in the duration.
2.
min_type minutes() const;
Returns normalized number of minutes.
3.
sec_type seconds() const;
Returns normalized number of seconds (0..60).
4.
sec_type total_seconds() const;
Returns total number of seconds truncating any fractional seconds.
5.
tick_type total_milliseconds() const;
Returns total number of milliseconds truncating any fractional seconds.
6.
tick_type total_nanoseconds() const;
Returns total number of nanoseconds truncating any sub millisecond values.
7.
tick_type total_microseconds() const;
Returns total number of microseconds truncating any sub microsecond values.
8.
fractional_seconds_type fractional_seconds() const;
Returns count of fractional seconds at given resolution.
9.
duration_type invert_sign() const;
10.
bool
is_negative() const;
11.
bool
operator
<(const time_duration & rhs) const;
12.
bool
operator
==(const time_duration & rhs) const;
13.
duration_type operator-() const;
unary- Allows for time_duration td = -td1
14.
duration_type operator-(const duration_type & d) const;
15.
duration_type operator+(const duration_type & d) const;
16.
duration_type operator/(int divisor) ;
17.
duration_type operator-=(const duration_type & d) ;
18.
duration_type operator+=(const duration_type & d) ;
19.
duration_type operator/=(int divisor) ;
Division operations on a duration with an integer.
20.
duration_type operator *(int rhs) const;
Multiplication operations an a duration with an integer.
21.
duration_type operator *=(int divisor) ;
22.
tick_type ticks() const;
23.
bool
is_special() const;
Is ticks_ a special value?
24.
bool
is_pos_infinity() const;
Is duration pos-infinity.
25.
bool
is_neg_infinity() const;
Is duration neg-infinity.
26.
bool
is_not_a_date_time() const;
Is duration not-a-date-time.
27.
impl_type get_rep() const;
Used for special_values output.
time_duration public static functions
time_duration
public static functions
1.
duration_type unit() ;
Returns smallest representable duration.
2.
tick_type ticks_per_second() ;
Return the number of ticks in a second.
3.
time_resolutions resolution() ;
Provide the resolution of this duration type.
4.
unsigned
short
num_fractional_digits() ;
Returns number of possible digits in fractional seconds.
time_duration protected member functions
time_duration
protected member functions
Class template subsecond_duration
Class template subsecond_duration -- Template for instantiating derived adjusting durations.
boost::date_time::subsecond_duration
template
<typename base_duration, long frac_of_second> class subsecond_duration { public: // types typedef base_duration::traits_type traits_type;

// construct/copy/destruct
subsecond_duration
(long);

// public member functions
};
Description
Description
subsecond_duration construct/copy/destruct
subsecond_duration
construct/copy/destruct
1.
subsecond_duration(long ss);
subsecond_duration public member functions
subsecond_duration
public member functions
Header <boost/date_time/time_formatting_streams.hpp>
namespace
boost { namespace date_time { template<typename time_duration_type, typename charT = char> class ostream_time_duration_formatter; template<typename time_type, typename charT = char> class ostream_time_formatter; template<typename time_period_type, typename charT = char> class ostream_time_period_formatter; } }
Class template ostream_time_duration_formatter
Class template ostream_time_duration_formatter -- Put a time type into a stream using appropriate facets.
boost::date_time::ostream_time_duration_formatter
template
<typename time_duration_type, typename charT = char> class ostream_time_duration_formatter { public: // types typedef std::basic_ostream< charT > ostream_type; typedef time_duration_type::fractional_seconds_type fractional_seconds_type;

// public static functions
void
duration_put
(const time_duration_type &, ostream_type &) ; };
Description
Description
ostream_time_duration_formatter public static functions
ostream_time_duration_formatter
public static functions
1.
void
duration_put(const time_duration_type & td, ostream_type & os) ;
Put time into an ostream.
Class template ostream_time_formatter
Class template ostream_time_formatter -- Put a time type into a stream using appropriate facets.
boost::date_time::ostream_time_formatter
template
<typename time_type, typename charT = char> class ostream_time_formatter { public: // types typedef std::basic_ostream< charT > ostream_type; typedef time_type::date_type date_type; typedef time_type::time_duration_type time_duration_type; typedef ostream_time_duration_formatter< time_duration_type, charT > duration_formatter;

// public static functions
void
time_put
(const time_type &, ostream_type &) ; };
Description
Description
ostream_time_formatter public static functions
ostream_time_formatter
public static functions
1.
void
time_put(const time_type & t, ostream_type & os) ;
Put time into an ostream.
Class template ostream_time_period_formatter
Class template ostream_time_period_formatter -- Put a time period into a stream using appropriate facets.
boost::date_time::ostream_time_period_formatter
template
<typename time_period_type, typename charT = char> class ostream_time_period_formatter { public: // types typedef std::basic_ostream< charT > ostream_type; typedef time_period_type::point_type time_type; typedef ostream_time_formatter< time_type, charT > time_formatter;

// public static functions
void
period_put
(const time_period_type &, ostream_type &) ; };
Description
Description
ostream_time_period_formatter public static functions
ostream_time_period_formatter
public static functions
1.
void
period_put(const time_period_type & tp, ostream_type & os) ;
Put time into an ostream.
Header <boost/date_time/time_iterator.hpp>
namespace
boost { namespace date_time { template<typename time_type> class time_itr; } }
Class template time_itr
Class template time_itr -- Simple time iterator skeleton class.
boost::date_time::time_itr
template
<typename time_type> class time_itr { public: // types typedef time_type::time_duration_type time_duration_type;

// construct/copy/destruct
time_itr
(time_type, time_duration_type);

// public member functions
time_itr
& operator++() ; time_itr & operator--() ; time_type operator *() ; time_type * operator->() ; bool operator<(const time_type &) ; bool operator<=(const time_type &) ; bool operator!=(const time_type &) ; bool operator==(const time_type &) ; bool operator>(const time_type &) ; bool operator>=(const time_type &) ; };
Description
Description
time_itr construct/copy/destruct
time_itr
construct/copy/destruct
1.
time_itr(time_type t, time_duration_type d);
time_itr public member functions
time_itr
public member functions
1.
time_itr
& operator++() ;
2.
time_itr
& operator--() ;
3.
time_type operator *() ;
4.
time_type * operator->() ;
5.
bool
operator
<(const time_type & t) ;
6.
bool
operator
<=(const time_type & t) ;
7.
bool
operator
!=(const time_type & t) ;
8.
bool
operator
==(const time_type & t) ;
9.
bool
operator
>(const time_type & t) ;
10.
bool
operator
>=(const time_type & t) ;
Header <boost/date_time/time_parsing.hpp>
namespace
boost { namespace date_time { template<typename time_duration> time_duration parse_delimited_time_duration(const std::string &);

// Utility function to split appart string.
bool
split(const std::string & s, char sep, std::string & first, std::string & second); template<typename time_type> time_type parse_delimited_time(const std::string & s, char sep);

// Parse time duration part of an iso time of form: [-]hhmmss (eg: 120259 is 12 hours 2 min 59 seconds).
template
<typename time_duration> time_duration parse_undelimited_time_duration(const std::string & s);

// Parse time string of form YYYYMMDDThhmmss where T is delimeter between date and time.
template
<typename time_type> time_type parse_iso_time(const std::string & s, char sep); } }
Function template parse_delimited_time_duration
Function template parse_delimited_time_duration -- Creates a time_duration object from a delimited string.
boost::date_time::parse_delimited_time_duration
template
<typename time_duration> time_duration parse_delimited_time_duration(const std::string & s);
Description
Description
Expected format for string is "[-]h[h][:mm][:ss][.fff]". A negative duration will be created if the first character in string is a '-', all other '-' will be treated as delimiters. Accepted delimiters are "-:,.".
Header <boost/date_time/time_resolution_traits.hpp>
namespace
boost { namespace date_time { struct time_resolution_traits_bi32_impl; struct time_resolution_traits_adapted32_impl; struct time_resolution_traits_bi64_impl; struct time_resolution_traits_adapted64_impl;

template
<typename frac_sec_type, time_resolutions res, #if(defined(BOOST_MSVC)&&(_MSC_VER<=1200)) boost::int64_t resolution_adjust, #else typename frac_sec_type::int_type resolution_adjust, #endif unsigned short frac_digits, typename v_type = boost::int32_t> class time_resolution_traits;

typedef
time_resolution_traits< time_resolution_traits_adapted32_impl, milli, 1000, 3 > milli_res; typedef time_resolution_traits< time_resolution_traits_adapted64_impl, micro, 1000000, 6 > micro_res; typedef time_resolution_traits< time_resolution_traits_adapted64_impl, nano, 1000000000, 9 > nano_res;

// Simple function to calculate absolute value of a numeric type.
template
<typename T> T absolute_value(T x); } }
Struct time_resolution_traits_bi32_impl
Struct time_resolution_traits_bi32_impl -- traits struct for time_resolution_traits implementation type
boost::date_time::time_resolution_traits_bi32_impl
struct
time_resolution_traits_bi32_impl { // types typedef boost::int32_t int_type; typedef boost::int32_t impl_type;

// public static functions
int_type as_number(impl_type) ; bool is_adapted() ; };
Description
Description
time_resolution_traits_bi32_impl public static functions
time_resolution_traits_bi32_impl
public static functions
1.
int_type as_number(impl_type i) ;
2.
bool
is_adapted() ;
Used to determine if implemented type is int_adapter or int.
Struct time_resolution_traits_adapted32_impl
Struct time_resolution_traits_adapted32_impl -- traits struct for time_resolution_traits implementation type
boost::date_time::time_resolution_traits_adapted32_impl
struct
time_resolution_traits_adapted32_impl { // types typedef boost::int32_t int_type; typedef boost::date_time::int_adapter< boost::int32_t > impl_type;

// public static functions
int_type as_number(impl_type) ; bool is_adapted() ; };
Description
Description
time_resolution_traits_adapted32_impl public static functions
time_resolution_traits_adapted32_impl
public static functions
1.
int_type as_number(impl_type i) ;
2.
bool
is_adapted() ;
Used to determine if implemented type is int_adapter or int.
Struct time_resolution_traits_bi64_impl
Struct time_resolution_traits_bi64_impl -- traits struct for time_resolution_traits implementation type
boost::date_time::time_resolution_traits_bi64_impl
struct
time_resolution_traits_bi64_impl { // types typedef boost::int64_t int_type; typedef boost::int64_t impl_type;

// public static functions
int_type as_number(impl_type) ; bool is_adapted() ; };
Description
Description
time_resolution_traits_bi64_impl public static functions
time_resolution_traits_bi64_impl
public static functions
1.
int_type as_number(impl_type i) ;
2.
bool
is_adapted() ;
Used to determine if implemented type is int_adapter or int.
Struct time_resolution_traits_adapted64_impl
Struct time_resolution_traits_adapted64_impl -- traits struct for time_resolution_traits implementation type
boost::date_time::time_resolution_traits_adapted64_impl
struct
time_resolution_traits_adapted64_impl { // types typedef boost::int64_t int_type; typedef boost::date_time::int_adapter< boost::int64_t > impl_type;

// public static functions
int_type as_number(impl_type) ; bool is_adapted() ; };
Description
Description
time_resolution_traits_adapted64_impl public static functions
time_resolution_traits_adapted64_impl
public static functions
1.
int_type as_number(impl_type i) ;
2.
bool
is_adapted() ;
Used to determine if implemented type is int_adapter or int.
Class template time_resolution_traits
Class template time_resolution_traits --
boost::date_time::time_resolution_traits
template
<typename frac_sec_type, time_resolutions res, #if(defined(BOOST_MSVC)&&(_MSC_VER<=1200)) boost::int64_t resolution_adjust, #else typename frac_sec_type::int_type resolution_adjust, #endif unsigned short frac_digits, typename v_type = boost::int32_t> class time_resolution_traits { public: // types typedef frac_sec_type::int_type fractional_seconds_type; typedef frac_sec_type::int_type tick_type; typedef frac_sec_type::impl_type impl_type; typedef v_type day_type; typedef v_type hour_type; typedef v_type min_type; typedef v_type sec_type;

// public member functions
BOOST_STATIC_CONSTANT
(int, ticks_per_second = resolution_adjust) ;

// public static functions
frac_sec_type::int_type as_number(typename frac_sec_type::impl_type) ; bool is_adapted() ; time_resolutions resolution() ; unsigned short num_fractional_digits() ; fractional_seconds_type res_adjust() ; tick_type to_tick_count(hour_type, min_type, sec_type, fractional_seconds_type) ; };
Description
Description
time_resolution_traits public member functions
time_resolution_traits
public member functions
1.
BOOST_STATIC_CONSTANT(int , ticks_per_second = resolution_adjust) ;
time_resolution_traits public static functions
time_resolution_traits
public static functions
1.
frac_sec_type::int_type as_number(typename frac_sec_type::impl_type i) ;
2.
bool
is_adapted() ;
3.
time_resolutions resolution() ;
4.
unsigned
short
num_fractional_digits() ;
5.
fractional_seconds_type res_adjust() ;
6.
tick_type to_tick_count(hour_type hours, min_type minutes, sec_type seconds, fractional_seconds_type fs) ;
Any negative argument results in a negative tick_count.
Header <boost/date_time/time_system_counted.hpp>
namespace
boost { namespace date_time { template<typename config> struct counted_time_rep;

template
<typename time_rep> class counted_time_system; } }
Struct template counted_time_rep
Struct template counted_time_rep -- Time representation that uses a single integer count.
boost::date_time::counted_time_rep
template
<typename config> struct counted_time_rep { // types typedef config::int_type int_type; typedef config::date_type date_type; typedef config::impl_type impl_type; typedef date_type::duration_type date_duration_type; typedef date_type::calendar_type calendar_type; typedef date_type::ymd_type ymd_type; typedef config::time_duration_type time_duration_type; typedef config::resolution_traits resolution_traits;

// construct/copy/destruct
counted_time_rep
(const date_type &, const time_duration_type &); counted_time_rep(int_type); counted_time_rep(impl_type);

// public member functions
date_type date() const; int_type day_count() const; int_type time_count() const; int_type tod() const; bool is_pos_infinity() const; bool is_neg_infinity() const; bool is_not_a_date_time() const; bool is_special() const; impl_type get_rep() const;

// public static functions
int_type frac_sec_per_day() ; };
Description
Description
counted_time_rep construct/copy/destruct
counted_time_rep
construct/copy/destruct
1.
counted_time_rep(const date_type & d, const time_duration_type & tod);
2.
counted_time_rep(int_type count);
3.
counted_time_rep(impl_type count);
counted_time_rep public member functions
counted_time_rep
public member functions
1.
date_type date() const;
2.
int_type day_count() const;
3.
int_type time_count() const;
4.
int_type tod() const;
5.
bool
is_pos_infinity() const;
6.
bool
is_neg_infinity() const;
7.
bool
is_not_a_date_time() const;
8.
bool
is_special() const;
9.
impl_type get_rep() const;
counted_time_rep public static functions
counted_time_rep
public static functions
1.
int_type frac_sec_per_day() ;
Class template counted_time_system
Class template counted_time_system -- An unadjusted time system implementation.
boost::date_time::counted_time_system
template
<typename time_rep> class counted_time_system { public: // types typedef time_rep time_rep_type; typedef time_rep_type::impl_type impl_type; typedef time_rep_type::time_duration_type time_duration_type; typedef time_duration_type::fractional_seconds_type fractional_seconds_type; typedef time_rep_type::date_type date_type; typedef time_rep_type::date_duration_type date_duration_type;

// public static functions
template
<typename T> void unused_var(const T &) ; time_rep_type get_time_rep(const date_type &, const time_duration_type &, date_time::dst_flags = not_dst) ; date_type get_date(const time_rep_type &) ; time_duration_type get_time_of_day(const time_rep_type &) ; std::string zone_name(const time_rep_type &) ; bool is_equal(const time_rep_type &, const time_rep_type &) ; bool is_less(const time_rep_type &, const time_rep_type &) ; time_rep_type add_days(const time_rep_type &, const date_duration_type &) ; time_rep_type subtract_days(const time_rep_type &, const date_duration_type &) ; time_rep_type subtract_time_duration(const time_rep_type &, const time_duration_type &) ; time_rep_type add_time_duration(const time_rep_type &, time_duration_type) ; time_duration_type subtract_times(const time_rep_type &, const time_rep_type &) ; };
Description
Description
counted_time_system public static functions
counted_time_system
public static functions
1.
template
<typename T> void unused_var(const T & ) ;
2.
time_rep_type get_time_rep(const date_type & day, const time_duration_type & tod, date_time::dst_flags dst = not_dst) ;
3.
date_type get_date(const time_rep_type & val) ;
4.
time_duration_type get_time_of_day(const time_rep_type & val) ;
5.
std::string zone_name(const time_rep_type & ) ;
6.
bool
is_equal(const time_rep_type & lhs, const time_rep_type & rhs) ;
7.
bool
is_less(const time_rep_type & lhs, const time_rep_type & rhs) ;
8.
time_rep_type add_days(const time_rep_type & base, const date_duration_type & dd) ;
9.
time_rep_type subtract_days(const time_rep_type & base, const date_duration_type & dd) ;
10.
time_rep_type subtract_time_duration(const time_rep_type & base, const time_duration_type & td) ;
11.
time_rep_type add_time_duration(const time_rep_type & base, time_duration_type td) ;
12.
time_duration_type subtract_times(const time_rep_type & lhs, const time_rep_type & rhs) ;
Header <boost/date_time/time_system_split.hpp>
namespace
boost { namespace date_time { template<typename config, boost::int32_t ticks_per_second> class split_timedate_system; } }
Class template split_timedate_system
Class template split_timedate_system -- An unadjusted time system implementation.
boost::date_time::split_timedate_system
template
<typename config, boost::int32_t ticks_per_second> class split_timedate_system { public: // types typedef config::time_rep_type time_rep_type; typedef config::date_type date_type; typedef config::time_duration_type time_duration_type; typedef config::date_duration_type date_duration_type; typedef config::int_type int_type; typedef config::resolution_traits resolution_traits; typedef date_time::wrapping_int< int_type, INT64_C(86400)*ticks_per_second wrap_int_type; typedef date_time::wrapping_int< int_type, ticks_per_day > wrap_int_type;

// public static functions
time_rep_type get_time_rep(const date_type &, const time_duration_type &, date_time::dst_flags = not_dst) ; date_type get_date(const time_rep_type &) ; time_duration_type get_time_of_day(const time_rep_type &) ; std::string zone_name(const time_rep_type &) ; bool is_equal(const time_rep_type &, const time_rep_type &) ; bool is_less(const time_rep_type &, const time_rep_type &) ; time_rep_type add_days(const time_rep_type &, const date_duration_type &) ; time_rep_type subtract_days(const time_rep_type &, const date_duration_type &) ; time_rep_type subtract_time_duration(const time_rep_type &, const time_duration_type &) ; time_rep_type add_time_duration(const time_rep_type &, time_duration_type) ; time_duration_type subtract_times(const time_rep_type &, const time_rep_type &) ;

// private member functions
BOOST_STATIC_CONSTANT
(int_type, ticks_per_day = INT64_C(86400)*config::tick_per_second) ; };
Description
Description
split_timedate_system public static functions
split_timedate_system
public static functions
1.
time_rep_type get_time_rep(const date_type & day, const time_duration_type & tod, date_time::dst_flags dst = not_dst) ;
2.
date_type get_date(const time_rep_type & val) ;
3.
time_duration_type get_time_of_day(const time_rep_type & val) ;
4.
std::string zone_name(const time_rep_type & ) ;
5.
bool
is_equal(const time_rep_type & lhs, const time_rep_type & rhs) ;
6.
bool
is_less(const time_rep_type & lhs, const time_rep_type & rhs) ;
7.
time_rep_type add_days(const time_rep_type & base, const date_duration_type & dd) ;
8.
time_rep_type subtract_days(const time_rep_type & base, const date_duration_type & dd) ;
9.
time_rep_type subtract_time_duration(const time_rep_type & base, const time_duration_type & td) ;
10.
time_rep_type add_time_duration(const time_rep_type & base, time_duration_type td) ;
11.
time_duration_type subtract_times(const time_rep_type & lhs, const time_rep_type & rhs) ;
split_timedate_system private member functions
split_timedate_system
private member functions
1.
BOOST_STATIC_CONSTANT(int_type , ticks_per_day = INT64_C(86400)*config::tick_per_second) ;
Header <boost/date_time/wrapping_int.hpp>
namespace
boost { namespace date_time { template<typename int_type_, int_type_ wrap_val> class wrapping_int; template<typename int_type_, int_type_ wrap_min, int_type_ wrap_max> class wrapping_int2; } }
Class template wrapping_int
Class template wrapping_int -- A wrapping integer used to support time durations.
boost::date_time::wrapping_int
template
<typename int_type_, int_type_ wrap_val> class wrapping_int { public: // types typedef int_type_ int_type;

// construct/copy/destruct
wrapping_int
(int_type);

// public member functions
int_type as_int() const; operator int_type() const; int_type add(int_type) ; int_type subtract(int_type) ;

// public static functions
int_type wrap_value() ; };
Description
Description
In composite date and time types this type is used to wrap at the day boundary.
wrapping_int construct/copy/destruct
wrapping_int
construct/copy/destruct
1.
wrapping_int(int_type v);
Add, return true if wrapped.
wrapping_int public member functions
wrapping_int
public member functions
1.
int_type as_int() const;
Explicit converion method.
2.
operator
int_type() const;
3.
int_type add(int_type v) ;
4.
int_type subtract(int_type v) ;
wrapping_int public static functions
wrapping_int
public static functions
1.
int_type wrap_value() ;
Class template wrapping_int2
Class template wrapping_int2 -- A wrapping integer used to wrap around at the top.
boost::date_time::wrapping_int2
template
<typename int_type_, int_type_ wrap_min, int_type_ wrap_max> class wrapping_int2 { public: // types typedef int_type_ int_type;

// construct/copy/destruct
wrapping_int2
(int_type);

// public member functions
int_type as_int() const; operator int_type() const; int_type add(int_type) ; int_type subtract(int_type) ;

// public static functions
unsigned
long
wrap_value
() ; unsigned long min_value() ; };
Description
Description
Bad name, quick impl to fix a bug -- fix later!! This allows the wrap to restart at a value other than 0. Currently this only works if wrap_min == 1
wrapping_int2 construct/copy/destruct
wrapping_int2
construct/copy/destruct
1.
wrapping_int2(int_type v);
If initializing value is out of range of [wrap_min, wrap_max], value will be initialized to closest of min or max
wrapping_int2 public member functions
wrapping_int2
public member functions
1.
int_type as_int() const;
Explicit converion method.
2.
operator
int_type() const;
3.
int_type add(int_type v) ;
Add, return number of wraps performed.
4.
int_type subtract(int_type v) ;
Subtract will return '-d' if wrapping took place ('d' is the number of wraps).
wrapping_int2 public static functions
wrapping_int2
public static functions
1.
unsigned
long
wrap_value() ;
2.
unsigned
long
min_value() ;
Header <boost/date_time/year_month_day.hpp>
namespace
boost { namespace date_time { template<typename YearType, typename MonthType, typename DayType> struct year_month_day_base; } }
Struct template year_month_day_base
Struct template year_month_day_base -- Allow rapid creation of ymd triples of different types.
boost::date_time::year_month_day_base
template
<typename YearType, typename MonthType, typename DayType> struct year_month_day_base { // types typedef YearType year_type; typedef MonthType month_type; typedef DayType day_type;

// construct/copy/destruct
year_month_day_base
(YearType, MonthType, DayType);

// public member functions

YearType year; MonthType month; DayType day; };
Description
Description
year_month_day_base construct/copy/destruct
year_month_day_base
construct/copy/destruct
1.
year_month_day_base(YearType year, MonthType month, DayType day);
A basic constructor.
year_month_day_base public member functions
year_month_day_base
public member functions
Gregorian Reference
Header <boost/date_time/gregorian/formatters.hpp>
namespace
boost { namespace gregorian { template<typename charT> std::basic_string< charT > to_simple_string_type(const date & d);

// To YYYY-mmm-DD string where mmm 3 char month name. Example: 2002-Jan-01.
std::string to_simple_string(const date & d); template<typename charT> std::basic_string< charT > to_simple_string_type(const date_period & d);

// Convert date period to simple string. Example: [2002-Jan-01/2002-Jan-02].
std::string to_simple_string(const date_period & d); template<typename charT> std::basic_string< charT > to_iso_string_type(const date_period & d);

// Date period to iso standard format CCYYMMDD/CCYYMMDD. Example: 20021225/20021231.
std::string to_iso_string(const date_period & d); template<typename charT> std::basic_string< charT > to_iso_extended_string_type(const date & d);

// Convert to iso extended format string CCYY-MM-DD. Example 2002-12-31.
std::string to_iso_extended_string(const date & d); template<typename charT> std::basic_string< charT > to_iso_string_type(const date & d);

// Convert to iso standard string YYYYMMDD. Example: 20021231.
std::string to_iso_string(const date & d); template<typename charT> std::basic_string< charT > to_sql_string_type(const date & d); std::string to_sql_string(const date & d);

// Convert date period to simple string. Example: [2002-Jan-01/2002-Jan-02].
std::wstring to_simple_wstring(const date_period & d);

// To YYYY-mmm-DD string where mmm 3 char month name. Example: 2002-Jan-01.
std::wstring to_simple_wstring(const date & d);

// Date period to iso standard format CCYYMMDD/CCYYMMDD. Example: 20021225/20021231.
std::wstring to_iso_wstring(const date_period & d);

// Convert to iso extended format string CCYY-MM-DD. Example 2002-12-31.
std::wstring to_iso_extended_wstring(const date & d);

// Convert to iso standard string YYYYMMDD. Example: 20021231.
std::wstring to_iso_wstring(const date & d); std::wstring to_sql_wstring(const date & d); } }
Header <boost/date_time/gregorian/formatters_limited.hpp>
namespace
boost { namespace gregorian { } }
Header <boost/date_time/gregorian/greg_calendar.hpp>
namespace
boost { namespace gregorian { class gregorian_calendar;

typedef
date_time::int_adapter< unsigned long > fancy_date_rep; // An internal date representation that includes infinities, not a date. } }
Class gregorian_calendar
Class gregorian_calendar -- Gregorian calendar for this implementation, hard work in the base.
boost::gregorian::gregorian_calendar
class
gregorian_calendar { public: // types typedef greg_weekday day_of_week_type; // Type to hold a weekday (eg: Sunday, Monday,...). typedef greg_day_of_year_rep day_of_year_type; // Counter type from 1 to 366 for gregorian dates. typedef fancy_date_rep date_rep_type; // Internal date representation that handles infinity, not a date. typedef fancy_date_rep date_traits_type; // Date rep implements the traits stuff as well. };
Header <boost/date_time/gregorian/greg_date.hpp>
namespace
boost { namespace gregorian { class date; } }
Class date
Class date -- A date type based on gregorian_calendar.
boost::gregorian::date
class
date { public: // types typedef gregorian_calendar::year_type year_type; typedef gregorian_calendar::month_type month_type; typedef gregorian_calendar::day_type day_type; typedef gregorian_calendar::day_of_year_type day_of_year_type; typedef gregorian_calendar::ymd_type ymd_type; typedef gregorian_calendar::date_rep_type date_rep_type; typedef gregorian_calendar::date_int_type date_int_type; typedef date_duration duration_type;

// construct/copy/destruct
date
(); date(year_type, month_type, day_type); date(const ymd_type &); date(const date_int_type &); date(date_rep_type); date(special_values);

// public member functions
date_int_type julian_day() const; day_of_year_type day_of_year() const; long modjulian_day() const; int week_number() const; date_int_type day_number() const; };
Description
Description
This class is the primary interface for programming with greogorian dates. The is a lightweight type that can be freely passed by value. All comparison operators are supported.
date construct/copy/destruct
date
construct/copy/destruct
1.
date();
Default constructor constructs with not_a_date_time.
2.
date(year_type y, month_type m, day_type d);
Main constructor with year, month, day.
3.
date(const ymd_type & ymd);
Constructor from a ymd_type structure.
4.
date(const date_int_type & rhs);
Needed copy constructor.
5.
date(date_rep_type rhs);
Needed copy constructor.
6.
date(special_values sv);
Constructor for infinities, not a date, max and min date.
date public member functions
date
public member functions
1.
date_int_type julian_day() const;
Return the Julian Day number for the date.
2.
day_of_year_type day_of_year() const;
Return the day of year 1..365 or 1..366 (for leap year).
3.
long
modjulian_day() const;
Return the Modified Julian Day number for the date.
4.
int
week_number() const;
Return the iso 8601 week number 1..53.
5.
date_int_type day_number() const;
Return the day number from the calendar.
Header <boost/date_time/gregorian/greg_day.hpp>
namespace
boost { namespace gregorian { struct bad_day_of_month;

class
greg_day
;

typedef
CV::simple_exception_policy< unsigned short, 1, 31, bad_day_of_month > greg_day_policies; // Policy class that declares error handling and day of month ranges. typedef CV::constrained_value< greg_day_policies > greg_day_rep; // Generated represetation for gregorian day of month. } }
Struct bad_day_of_month
Struct bad_day_of_month -- Exception type for gregorian day of month (1..31).
boost::gregorian::bad_day_of_month
struct
bad_day_of_month { // construct/copy/destruct bad_day_of_month(); bad_day_of_month(const std::string &);

// public member functions
};
Description
Description
bad_day_of_month construct/copy/destruct
bad_day_of_month
construct/copy/destruct
1.
bad_day_of_month();
2.
bad_day_of_month(const std::string & s);
Allow other classes to throw with unique string for bad day like Feb 29.
bad_day_of_month public member functions
bad_day_of_month
public member functions
Class greg_day
Class greg_day -- Represent a day of the month (range 1 - 31).
boost::gregorian::greg_day
class
greg_day { public: // construct/copy/destruct greg_day(unsigned short);

// public member functions
unsigned
short
as_number
() const; operator unsigned short() const; };
Description
Description
This small class allows for simple conversion an integer value into a day of the month for a standard gregorian calendar. The type is automatically range checked so values outside of the range 1-31 will cause a bad_day_of_month exception
greg_day construct/copy/destruct
greg_day
construct/copy/destruct
1.
greg_day(unsigned short day_of_month);
greg_day public member functions
greg_day
public member functions
1.
unsigned
short
as_number() const;
2.
operator
unsigned
short
() const;
Header <boost/date_time/gregorian/greg_day_of_year.hpp>
namespace
boost { namespace gregorian { struct bad_day_of_year;

typedef
CV::simple_exception_policy< unsigned short, 1, 366, bad_day_of_year > greg_day_of_year_policies; // A day of the year range (1..366). typedef CV::constrained_value< greg_day_of_year_policies > greg_day_of_year_rep; // Define a range representation type for the day of the year 1..366. } }
Struct bad_day_of_year
Struct bad_day_of_year -- Exception type for day of year (1..366).
boost::gregorian::bad_day_of_year
struct
bad_day_of_year { // construct/copy/destruct bad_day_of_year();

// public member functions
};
Description
Description
bad_day_of_year construct/copy/destruct
bad_day_of_year
construct/copy/destruct
1.
bad_day_of_year();
bad_day_of_year public member functions
bad_day_of_year
public member functions
Header <boost/date_time/gregorian/greg_duration.hpp>
namespace
boost { namespace gregorian { typedef boost::date_time::duration_traits_adapted date_duration_rep; // An internal date representation that includes infinities, not a date. typedef date_time::date_duration< date_duration_rep > date_duration; // Durations in days for gregorian system. typedef date_duration days; // Shorthand for date_duration. } }
Header <boost/date_time/gregorian/greg_duration_types.hpp>
namespace
boost { namespace gregorian { struct greg_durations_config;

typedef
date_time::months_duration< greg_durations_config > months; typedef date_time::years_duration< greg_durations_config > years; typedef date_time::weeks_duration< date_time::duration_traits_adapted > weeks; } }
Struct greg_durations_config
Struct greg_durations_config -- config struct for additional duration types (ie months_duration<> & years_duration<>)
boost::gregorian::greg_durations_config
struct
greg_durations_config { // types typedef date date_type; typedef date_time::int_adapter< int > int_rep; typedef date_time::month_functor< date_type > month_adjustor_type; };
Header <boost/date_time/gregorian/greg_facet.hpp>
namespace
boost { namespace gregorian { struct greg_facet_config;

typedef
boost::date_time::date_names_put< greg_facet_config > greg_base_facet; // Create the base facet type for gregorian::date. template<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > &, const date &); template<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > &, const greg_month &); template<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > &, const greg_weekday &); template<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > &, const date_period &); template<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const date_duration & dd);

// operator<< for gregorian::partial_date. Output: "Jan 1"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const partial_date & pd);

// operator<< for gregorian::nth_kday_of_month. Output: "first Mon of Jun"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const nth_kday_of_month & nkd);

// operator<< for gregorian::first_kday_of_month. Output: "first Mon of Jun"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const first_kday_of_month & fkd);

// operator<< for gregorian::last_kday_of_month. Output: "last Mon of Jun"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const last_kday_of_month & lkd);

// operator<< for gregorian::first_kday_after. Output: "first Mon after"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const first_kday_after & fka);

// operator<< for gregorian::first_kday_before. Output: "first Mon before"
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const first_kday_before & fkb);

// operator>> for gregorian::date
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, date & d);

// operator>> for gregorian::date_duration
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, date_duration & dd);

// operator>> for gregorian::date_period
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, date_period & dp);

// generates a locale with the set of gregorian name-strings of type char*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale & loc, char type);

// Returns a pointer to a facet with a default set of names (English).
BOOST_DATE_TIME_DECL boost::date_time::all_date_names_put< greg_facet_config, char > * create_facet_def(char type);

// generates a locale with the set of gregorian name-strings of type wchar_t*
BOOST_DATE_TIME_DECL std::locale generate_locale(std::locale & loc, wchar_t type);

// Returns a pointer to a facet with a default set of names (English).
BOOST_DATE_TIME_DECL boost::date_time::all_date_names_put< greg_facet_config, wchar_t > * create_facet_def(wchar_t type);

// operator>> for gregorian::greg_month - throws exception if invalid month given
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, greg_month & m);

// operator>> for gregorian::greg_weekday - throws exception if invalid weekday given
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, greg_weekday & wd); } }
Struct greg_facet_config
Struct greg_facet_config -- Configuration of the output facet template.
boost::gregorian::greg_facet_config
struct
greg_facet_config { // types typedef boost::gregorian::greg_month month_type; typedef boost::date_time::special_values special_value_enum; typedef boost::gregorian::months_of_year month_enum; typedef boost::date_time::weekdays weekday_enum; };
Function template operator<<
Function template operator<< -- ostream operator for gregorian::date
boost::gregorian::operator<<
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const date & d);
Description
Description
Uses the date facet to determine various output parameters including:•string values for the month (eg: Jan, Feb, Mar) (default: English)•string values for special values (eg: not-a-date-time) (default: English)•selection of long, short strings, or numerical month representation (default: short string)•month day year order (default yyyy-mmm-dd)
Function template operator<<
Function template operator<< -- operator<< for gregorian::greg_month typically streaming: Jan, Feb, Mar...
boost::gregorian::operator<<
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const greg_month & m);
Description
Description
Uses the date facet to determine output string as well as selection of long or short strings. Default if no facet is installed is to output a 2 wide numeric value for the month eg: 01 == Jan, 02 == Feb, ... 12 == Dec.
Function template operator<<
Function template operator<< -- operator<< for gregorian::greg_weekday typically streaming: Sun, Mon, Tue, ...
boost::gregorian::operator<<
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const greg_weekday & wd);
Description
Description
Uses the date facet to determine output string as well as selection of long or short string. Default if no facet is installed is to output a 3 char english string for the day of the week.
Function template operator<<
Function template operator<< -- operator<< for gregorian::date_period typical output: [2002-Jan-01/2002-Jan-31]
boost::gregorian::operator<<
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const date_period & dp);
Description
Description
Uses the date facet to determine output string as well as selection of long or short string fr dates. Default if no facet is installed is to output a 3 char english string for the day of the week.
Header <boost/date_time/gregorian/greg_month.hpp>
namespace
boost { namespace gregorian { struct bad_month;

class
greg_month
;

typedef
date_time::months_of_year months_of_year; typedef CV::simple_exception_policy< unsigned short, 1, 12, bad_month > greg_month_policies; // Build a policy class for the greg_month_rep. typedef CV::constrained_value< greg_month_policies > greg_month_rep; // A constrained range that implements the gregorian_month rules. } }
Struct bad_month
Struct bad_month -- Exception thrown if a greg_month is constructed with a value out of range.
boost::gregorian::bad_month
struct
bad_month { // construct/copy/destruct bad_month();

// public member functions
};
Description
Description
bad_month construct/copy/destruct
bad_month
construct/copy/destruct
1.
bad_month();
bad_month public member functions
bad_month
public member functions
Class greg_month
Class greg_month -- Wrapper class to represent months in gregorian based calendar.
boost::gregorian::greg_month
class
greg_month { public: // types typedef date_time::months_of_year month_enum; typedef std::map< std::string, unsigned short > month_map_type; typedef boost::shared_ptr< month_map_type > month_map_ptr_type;

// construct/copy/destruct
greg_month
(month_enum); greg_month(unsigned short);

// public member functions
operator
unsigned
short
() const; unsigned short as_number() const; month_enum as_enum() const; const char * as_short_string() const; const char * as_long_string() const; const wchar_t * as_short_wstring() const; const wchar_t * as_long_wstring() const; const char * as_short_string(char) const; const char * as_long_string(char) const; const wchar_t * as_short_string(wchar_t) const; const wchar_t * as_long_string(wchar_t) const;

// public static functions
month_map_ptr_type get_month_map_ptr() ; };
Description
Description
greg_month construct/copy/destruct
greg_month
construct/copy/destruct
1.
greg_month(month_enum theMonth);
Construct a month from the months_of_year enumeration.
2.
greg_month(unsigned short theMonth);
Construct from a short value.
greg_month public member functions
greg_month
public member functions
1.
operator
unsigned
short
() const;
Convert the value back to a short.
2.
unsigned
short
as_number() const;
Returns month as number from 1 to 12.
3.
month_enum as_enum() const;
4.
const
char
* as_short_string() const;
5.
const
char
* as_long_string() const;
6.
const
wchar_t
* as_short_wstring() const;
7.
const
wchar_t
* as_long_wstring() const;
8.
const
char
* as_short_string(char ) const;
9.
const
char
* as_long_string(char ) const;
10.
const
wchar_t
* as_short_string(wchar_t ) const;
11.
const
wchar_t
* as_long_string(wchar_t ) const;
greg_month public static functions
greg_month
public static functions
1.
month_map_ptr_type get_month_map_ptr() ;
Shared pointer to a map of Month strings (Names & Abbrev) & numbers.
Header <boost/date_time/gregorian/greg_weekday.hpp>
namespace
boost { namespace gregorian { struct bad_weekday;

class
greg_weekday
;

typedef
CV::simple_exception_policy< unsigned short, 0, 6, bad_weekday > greg_weekday_policies; typedef CV::constrained_value< greg_weekday_policies > greg_weekday_rep; } }
Struct bad_weekday
Struct bad_weekday -- Exception that flags that a weekday number is incorrect.
boost::gregorian::bad_weekday
struct
bad_weekday { // construct/copy/destruct bad_weekday();

// public member functions
};
Description
Description
bad_weekday construct/copy/destruct
bad_weekday
construct/copy/destruct
1.
bad_weekday();
bad_weekday public member functions
bad_weekday
public member functions
Class greg_weekday
Class greg_weekday -- Represent a day within a week (range 0==Sun to 6==Sat).
boost::gregorian::greg_weekday
class
greg_weekday { public: // types typedef boost::date_time::weekdays weekday_enum;

// construct/copy/destruct
greg_weekday
(unsigned short);

// public member functions
unsigned
short
as_number
() const; const char * as_short_string() const; const char * as_long_string() const; const wchar_t * as_short_wstring() const; const wchar_t * as_long_wstring() const; weekday_enum as_enum() const; };
Description
Description
greg_weekday construct/copy/destruct
greg_weekday
construct/copy/destruct
1.
greg_weekday(unsigned short day_of_week_num);
greg_weekday public member functions
greg_weekday
public member functions
1.
unsigned
short
as_number() const;
2.
const
char
* as_short_string() const;
3.
const
char
* as_long_string() const;
4.
const
wchar_t
* as_short_wstring() const;
5.
const
wchar_t
* as_long_wstring() const;
6.
weekday_enum as_enum() const;
Header <boost/date_time/gregorian/greg_year.hpp>
namespace
boost { namespace gregorian { struct bad_year;

class
greg_year
;

typedef
CV::simple_exception_policy< unsigned short, 1400, 10000, bad_year > greg_year_policies; // Policy class that declares error handling gregorian year type. typedef CV::constrained_value< greg_year_policies > greg_year_rep; // Generated representation for gregorian year. } }
Struct bad_year
Struct bad_year -- Exception type for gregorian year.
boost::gregorian::bad_year
struct
bad_year { // construct/copy/destruct bad_year();

// public member functions
};
Description
Description
bad_year construct/copy/destruct
bad_year
construct/copy/destruct
1.
bad_year();
bad_year public member functions
bad_year
public member functions
Class greg_year
Class greg_year -- Represent a day of the month (range 1900 - 10000).
boost::gregorian::greg_year
class
greg_year { public: // construct/copy/destruct greg_year(unsigned short);

// public member functions
operator
unsigned
short
() const; };
Description
Description
This small class allows for simple conversion an integer value into a year for the gregorian calendar. This currently only allows a range of 1900 to 10000. Both ends of the range are a bit arbitrary at the moment, but they are the limits of current testing of the library. As such they may be increased in the future.
greg_year construct/copy/destruct
greg_year
construct/copy/destruct
1.
greg_year(unsigned short year);
greg_year public member functions
greg_year
public member functions
1.
operator
unsigned
short
() const;
Header <boost/date_time/gregorian/greg_ymd.hpp>
namespace
boost { namespace gregorian { typedef date_time::year_month_day_base< greg_year, greg_month, greg_day > greg_year_month_day; } }
Header <boost/date_time/gregorian/gregorian.hpp>
Single file header that provides overall include for all elements of the gregorian date-time system. This includes the various types defined, but also other functions for formatting and parsing.
Header <boost/date_time/gregorian/gregorian_types.hpp>
Single file header that defines most of the types for the gregorian date-time system.
namespace
boost { namespace gregorian { typedef date_time::period< date, date_duration > date_period; // Date periods for the gregorian system. typedef date_time::year_based_generator< date > year_based_generator; // A unifying date_generator base type. typedef date_time::partial_date< date > partial_date; // A date generation object type. typedef date_time::nth_kday_of_month< date > nth_kday_of_month; typedef nth_kday_of_month nth_day_of_the_week_in_month; typedef date_time::first_kday_of_month< date > first_kday_of_month; typedef first_kday_of_month first_day_of_the_week_in_month; typedef date_time::last_kday_of_month< date > last_kday_of_month; typedef last_kday_of_month last_day_of_the_week_in_month; typedef date_time::first_kday_after< date > first_kday_after; typedef first_kday_after first_day_of_the_week_after; typedef date_time::first_kday_before< date > first_kday_before; typedef first_kday_before first_day_of_the_week_before; typedef date_time::day_clock< date > day_clock; // A clock to get the current day from the local computer. typedef date_time::date_itr_base< date > date_iterator; // Base date_iterator type for gregorian types. typedef date_time::date_itr< date_time::day_functor< date >, date > day_iterator; // A day level iterator. typedef date_time::date_itr< date_time::week_functor< date >, date > week_iterator; // A week level iterator. typedef date_time::date_itr< date_time::month_functor< date >, date > month_iterator; // A month level iterator. typedef date_time::date_itr< date_time::year_functor< date >, date > year_iterator; // A year level iterator. } }
Header <boost/date_time/gregorian/parsers.hpp>
namespace
boost { namespace gregorian {

// Deprecated: Use from_simple_string.
date
from_string(std::string s);

// From delimited date string where with order year-month-day eg: 2002-1-25 or 2003-Jan-25 (full month name is also accepted).
date
from_simple_string(std::string s);

// From delimited date string where with order year-month-day eg: 1-25-2003 or Jan-25-2003 (full month name is also accepted).
date
from_us_string(std::string s);

// From delimited date string where with order day-month-year eg: 25-1-2002 or 25-Jan-2003 (full month name is also accepted).
date
from_uk_string(std::string s);

// From iso type date string where with order year-month-day eg: 20020125.
date
from_undelimited_string(std::string s);

// From iso type date string where with order year-month-day eg: 20020125.
date
date_from_iso_string(const std::string & s);

// Stream should hold a date in the form of: 2002-1-25. Month number, abbrev, or name are accepted.
template
<typename iterator_type> date from_stream(iterator_type beg, iterator_type end);

// Function to parse a date_period from a string (eg: [2003-Oct-31/2003-Dec-25]).
date_period date_period_from_string(const std::string & s);

// Function to parse a date_period from a wstring (eg: [2003-Oct-31/2003-Dec-25]).
date_period date_period_from_wstring(const std::wstring & s); } }
Posix Time Reference
Header <boost/date_time/posix_time/conversion.hpp>
namespace
boost { namespace posix_time {

// Function that converts a time_t into a ptime.
ptime
from_time_t(std::time_t t); template<typename time_type> time_type from_ftime(const FILETIME &); } }
Function template from_ftime
Function template from_ftime -- Function to create a time object from an initialized FILETIME struct.
boost::posix_time::from_ftime
template
<typename time_type> time_type from_ftime(const FILETIME & ft);
Description
Description
Function to create a time object from an initialized FILETIME struct. A FILETIME struct holds 100-nanosecond units (0.0000001). When built with microsecond resolution the FILETIME's sub second value will be truncated. Nanosecond resolution has no truncation.
Note ftime is part of the Win32 API, so it is not portable to non-windows platforms.
Header <boost/date_time/posix_time/date_duration_operators.hpp>
Operators for ptime and optional gregorian types. Operators use snap-to-end-of-month behavior. Further details on this behavior can be found in reference for date_time/date_duration_types.hpp and documentation for month and year iterators.
namespace
boost { namespace posix_time { ptime operator+(const ptime &, const boost::gregorian::months &); ptime operator+=(ptime &, const boost::gregorian::months &); ptime operator-(const ptime &, const boost::gregorian::months &); ptime operator-=(ptime &, const boost::gregorian::months &); ptime operator+(const ptime &, const boost::gregorian::years &); ptime operator+=(ptime &, const boost::gregorian::years &); ptime operator-(const ptime &, const boost::gregorian::years &); ptime operator-=(ptime &, const boost::gregorian::years &); } }
Function operator+
Function operator+ --
boost::posix_time::operator+
ptime
operator
+(const ptime & t, const boost::gregorian::months & m);
Description
Description
Adds a months object and a ptime. Result will be same day-of-month as ptime unless original day was the last day of month. see date_time::months_duration for more details
Function operator+=
Function operator+= --
boost::posix_time::operator+=
ptime
operator
+=(ptime & t, const boost::gregorian::months & m);
Description
Description
Adds a months object to a ptime. Result will be same day-of-month as ptime unless original day was the last day of month. see date_time::months_duration for more details
Function operator-
Function operator- --
boost::posix_time::operator-
ptime
operator
-(const ptime & t, const boost::gregorian::months & m);
Description
Description
Subtracts a months object and a ptime. Result will be same day-of-month as ptime unless original day was the last day of month. see date_time::months_duration for more details
Function operator-=
Function operator-= --
boost::posix_time::operator-=
ptime
operator
-=(ptime & t, const boost::gregorian::months & m);
Description
Description
Subtracts a months object from a ptime. Result will be same day-of-month as ptime unless original day was the last day of month. see date_time::months_duration for more details
Function operator+
Function operator+ --
boost::posix_time::operator+
ptime
operator
+(const ptime & t, const boost::gregorian::years & y);
Description
Description
Adds a years object and a ptime. Result will be same month and day-of-month as ptime unless original day was the last day of month. see date_time::years_duration for more details
Function operator+=
Function operator+= --
boost::posix_time::operator+=
ptime
operator
+=(ptime & t, const boost::gregorian::years & y);
Description
Description
Adds a years object to a ptime. Result will be same month and day-of-month as ptime unless original day was the last day of month. see date_time::years_duration for more details
Function operator-
Function operator- --
boost::posix_time::operator-
ptime
operator
-(const ptime & t, const boost::gregorian::years & y);
Description
Description
Subtracts a years object and a ptime. Result will be same month and day-of-month as ptime unless original day was the last day of month. see date_time::years_duration for more details
Function operator-=
Function operator-= --
boost::posix_time::operator-=
ptime
operator
-=(ptime & t, const boost::gregorian::years & y);
Description
Description
Subtracts a years object from a ptime. Result will be same month and day-of-month as ptime unless original day was the last day of month. see date_time::years_duration for more details
Header <boost/date_time/posix_time/posix_time.hpp>
Global header file to get all of posix time types
Header <boost/date_time/posix_time/posix_time_config.hpp>
namespace
boost { namespace posix_time { class time_duration;

struct
simple_time_rep
;

class
posix_time_system_config
; class millisec_posix_time_system_config;

typedef
date_time::time_resolution_traits< boost::date_time::time_resolution_traits_adapted64_impl, boost::date_time::nano, 1000000000, 9 > time_res_traits; } }
Class time_duration
Class time_duration -- Base time duration type.
boost::posix_time::time_duration
class
time_duration { public: // types typedef time_res_traits rep_type; typedef time_res_traits::day_type day_type; typedef time_res_traits::hour_type hour_type; typedef time_res_traits::min_type min_type; typedef time_res_traits::sec_type sec_type; typedef time_res_traits::fractional_seconds_type fractional_seconds_type; typedef time_res_traits::tick_type tick_type; typedef time_res_traits::impl_type impl_type;

// construct/copy/destruct
time_duration
(hour_type, min_type, sec_type, fractional_seconds_type = 0); time_duration(); time_duration(boost::date_time::special_values); time_duration(impl_type);

// public member functions
// private member functions
};
Description
Description
time_duration construct/copy/destruct
time_duration
construct/copy/destruct
1.
time_duration(hour_type hour, min_type min, sec_type sec, fractional_seconds_type fs = 0);
2.
time_duration();
3.
time_duration(boost::date_time::special_values sv);
Construct from special_values.
4.
time_duration(impl_type ticks);
time_duration public member functions
time_duration
public member functions
time_duration private member functions
time_duration
private member functions
Struct simple_time_rep
Struct simple_time_rep -- Simple implementation for the time rep.
boost::posix_time::simple_time_rep
struct
simple_time_rep { // types typedef gregorian::date date_type; typedef time_duration time_duration_type;

// construct/copy/destruct
simple_time_rep
(date_type, time_duration_type);

// public member functions
bool
is_special
() const; bool is_pos_infinity() const; bool is_neg_infinity() const; bool is_not_a_date_time() const;

date_type day; time_duration_type time_of_day; };
Description
Description
simple_time_rep construct/copy/destruct
simple_time_rep
construct/copy/destruct
1.
simple_time_rep(date_type d, time_duration_type tod);
simple_time_rep public member functions
simple_time_rep
public member functions
1.
bool
is_special() const;
2.
bool
is_pos_infinity() const;
3.
bool
is_neg_infinity() const;
4.
bool
is_not_a_date_time() const;
Class posix_time_system_config
Class posix_time_system_config --
boost::posix_time::posix_time_system_config
class
posix_time_system_config { public: // types typedef simple_time_rep time_rep_type; typedef gregorian::date date_type; typedef gregorian::date_duration date_duration_type; typedef time_duration time_duration_type; typedef time_res_traits::tick_type int_type; typedef time_res_traits resolution_traits;

// public member functions
BOOST_STATIC_CONSTANT
(boost::int64_t, tick_per_second = 1000000000) ; };
Description
Description
posix_time_system_config public member functions
posix_time_system_config
public member functions
1.
BOOST_STATIC_CONSTANT(boost::int64_t , tick_per_second = 1000000000) ;
Class millisec_posix_time_system_config
Class millisec_posix_time_system_config --
boost::posix_time::millisec_posix_time_system_config
class
millisec_posix_time_system_config { public: // types typedef boost::int64_t time_rep_type; typedef gregorian::date date_type; typedef gregorian::date_duration date_duration_type; typedef time_duration time_duration_type; typedef time_res_traits::tick_type int_type; typedef time_res_traits::impl_type impl_type; typedef time_res_traits resolution_traits;

// public member functions
BOOST_STATIC_CONSTANT
(boost::int64_t, tick_per_second = 1000000) ; };
Description
Description
millisec_posix_time_system_config public member functions
millisec_posix_time_system_config
public member functions
1.
BOOST_STATIC_CONSTANT(boost::int64_t , tick_per_second = 1000000) ;
Header <boost/date_time/posix_time/posix_time_duration.hpp>
namespace
boost { namespace posix_time { class hours; class minutes; class seconds;

typedef
date_time::subsecond_duration< time_duration, 1000 > millisec; // Allows expression of durations as milli seconds. typedef date_time::subsecond_duration< time_duration, 1000 > milliseconds; typedef date_time::subsecond_duration< time_duration, 1000000 > microsec; // Allows expression of durations as micro seconds. typedef date_time::subsecond_duration< time_duration, 1000000 > microseconds; typedef date_time::subsecond_duration< time_duration, 1000000000 > nanosec; // Allows expression of durations as nano seconds. typedef date_time::subsecond_duration< time_duration, 1000000000 > nanoseconds; } }
Class hours
Class hours -- Allows expression of durations as an hour count.
boost::posix_time::hours
class
hours : public boost::posix_time::time_duration { public: // construct/copy/destruct hours(long);

// public member functions
};
Description
Description
hours construct/copy/destruct
hours
construct/copy/destruct
1.
hours(long h);
hours public member functions
hours
public member functions
Class minutes
Class minutes -- Allows expression of durations as a minute count.
boost::posix_time::minutes
class
minutes : public boost::posix_time::time_duration { public: // construct/copy/destruct minutes(long);

// public member functions
};
Description
Description
minutes construct/copy/destruct
minutes
construct/copy/destruct
1.
minutes(long m);
minutes public member functions
minutes
public member functions
Class seconds
Class seconds -- Allows expression of durations as a seconds count.
boost::posix_time::seconds
class
seconds : public boost::posix_time::time_duration { public: // construct/copy/destruct seconds(long);

// public member functions
};
Description
Description
seconds construct/copy/destruct
seconds
construct/copy/destruct
1.
seconds(long s);
seconds public member functions
seconds
public member functions
Header <boost/date_time/posix_time/posix_time_system.hpp>
namespace
boost { namespace posix_time { typedef date_time::split_timedate_system< posix_time_system_config, 1000000000 > posix_time_system; typedef date_time::counted_time_rep< millisec_posix_time_system_config > int64_time_rep; } }
Header <boost/date_time/posix_time/posix_time_types.hpp>
namespace
boost { namespace posix_time { typedef date_time::time_itr< ptime > time_iterator; // Iterator over a defined time duration. typedef date_time::second_clock< ptime::date_type, ptime > second_clock; // A time clock that has a resolution of one second. typedef date_time::microsec_clock< ptime > microsec_clock; // A time clock that has a resolution of one microsecond. typedef date_time::null_dst_rules< ptime::date_type, time_duration > no_dst; // Define a dst null dst rule for the posix_time system. typedef date_time::us_dst_rules< ptime::date_type, time_duration > us_dst; // Define US dst rule calculator for the posix_time system. } }
Header <boost/date_time/posix_time/ptime.hpp>
namespace
boost { namespace posix_time { class ptime; } }
Class ptime
Class ptime -- Time type with no timezone or other adjustments.
boost::posix_time::ptime
class
ptime { public: // types typedef posix_time_system time_system_type; typedef time_system_type::time_rep_type time_rep_type; typedef time_system_type::time_duration_type time_duration_type; typedef ptime time_type;

// construct/copy/destruct
ptime
(gregorian::date, time_duration_type); ptime(gregorian::date); ptime(const time_rep_type &); ptime(const special_values); ptime();

// public member functions
};
Description
Description
ptime construct/copy/destruct
ptime
construct/copy/destruct
1.
ptime(gregorian::date d, time_duration_type td);
Construct with date and offset in day.
2.
ptime(gregorian::date d);
Construct a time at start of the given day (midnight).
3.
ptime(const time_rep_type & rhs);
Copy from time_rep.
4.
ptime(const special_values sv);
Construct from special value.
5.
ptime();
ptime public member functions
ptime
public member functions
Header <boost/date_time/posix_time/time_formatters.hpp>
namespace
boost { namespace posix_time { template<typename charT> std::basic_string< charT > to_simple_string_type(time_duration td); template<typename charT> std::basic_string< charT > to_iso_string_type(time_duration td);

// Time to simple format CCYY-mmm-dd hh:mm:ss.fffffff.
template
<typename charT> std::basic_string< charT > to_simple_string_type(ptime t); template<typename charT> std::basic_string< charT > to_simple_string_type(time_period tp); template<typename charT> std::basic_string< charT > to_iso_string_type(ptime t); template<typename charT> std::basic_string< charT > to_iso_extended_string_type(ptime t);

// Time duration to wstring -hh::mm::ss.fffffff. Example: 10:09:03.0123456.
std::wstring to_simple_wstring(time_duration td);

// Time duration in iso format -hhmmss,fffffff Example: 10:09:03,0123456.
std::wstring to_iso_wstring(time_duration td); std::wstring to_simple_wstring(ptime t);

// Convert to wstring of form [YYYY-mmm-DD HH:MM::SS.ffffff/YYYY-mmm-DD HH:MM::SS.fffffff].
std::wstring to_simple_wstring(time_period tp);

// Convert iso short form YYYYMMDDTHHMMSS where T is the date-time separator.
std::wstring to_iso_wstring(ptime t);

// Convert to form YYYY-MM-DDTHH:MM:SS where T is the date-time separator.
std::wstring to_iso_extended_wstring(ptime t); template<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, time_duration & td); template<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, ptime & pt); template<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > &, time_period &); } }
Function template operator>>
Function template operator>> --
boost::posix_time::operator>>
template
<typename charT> std::basic_istream< charT > & operator>>(std::basic_istream< charT > & is, time_period & tp);
Description
Description
operator>> for time_period. time_period must be in "[date time_duration/date time_duration]" format.
Header <boost/date_time/posix_time/time_formatters_limited.hpp>
namespace
boost { namespace posix_time {

// Time duration to string -hh::mm::ss.fffffff. Example: 10:09:03.0123456.
std::string to_simple_string(time_duration td);

// Time duration in iso format -hhmmss,fffffff Example: 10:09:03,0123456.
std::string to_iso_string(time_duration td);

// Time to simple format CCYY-mmm-dd hh:mm:ss.fffffff.
std::string to_simple_string(ptime t);

// Convert to string of form [YYYY-mmm-DD HH:MM::SS.ffffff/YYYY-mmm-DD HH:MM::SS.fffffff].
std::string to_simple_string(time_period tp);

// Convert iso short form YYYYMMDDTHHMMSS where T is the date-time separator.
std::string to_iso_string(ptime t);

// Convert to form YYYY-MM-DDTHH:MM:SS where T is the date-time separator.
std::string to_iso_extended_string(ptime t);

// ostream operator for posix_time::time_duration
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const time_duration & td);

// ostream operator for posix_time::ptime
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const ptime & t);

// ostream operator for posix_time::time_period
template
<typename charT, typename traits> std::basic_ostream< charT, traits > & operator<<(std::basic_ostream< charT, traits > & os, const time_period & tp); } }
Header <boost/date_time/posix_time/time_parsers.hpp>
namespace
boost { namespace posix_time { time_duration duration_from_string(const std::string &); ptime time_from_string(const std::string & s); ptime from_iso_string(const std::string & s); } }
Function duration_from_string
Function duration_from_string -- Creates a time_duration object from a delimited string.
boost::posix_time::duration_from_string
time_duration
duration_from_string(const std::string & s);
Description
Description
Expected format for string is "[-]h[h][:mm][:ss][.fff]". A negative duration will be created if the first character in string is a '-', all other '-' will be treated as delimiters. Accepted delimiters are "-:,.".
Header <boost/date_time/posix_time/time_period.hpp>
namespace
boost { namespace posix_time { typedef date_time::period< ptime, time_duration > time_period; // Time period type. } }

Boost.Function

Boost.Function

Boost.Function
Douglas Gregor <dgregor -at- cs.indiana.edu>
Copyright © 2001-2004 Douglas Gregor
Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
The Boost.Function library contains a family of class templates that are function object wrappers. The notion is similar to a generalized callback. It shares features with function pointers in that both define a call interface (e.g., a function taking two integer arguments and returning a floating-point value) through which some implementation can be called, and the implementation that is invoked may change throughout the course of the program.
Generally, any place in which a function pointer would be used to defer a call or make a callback, Boost.Function can be used instead to allow the user greater flexibility in the implementation of the target. Targets can be any 'compatible' function object (or function pointer), meaning that the arguments to the interface designated by Boost.Function can be converted to the arguments of the target function object.
History & Compatibility Notes
History & Compatibility Notes
•
Version 1.30.0
:
•
All features deprecated in version 1.29.0 have been removed from Boost.Function.
•
boost::function
and boost::functionN objects can be assigned to 0 (semantically equivalent to calling clear()) and compared against 0 (semantically equivalent to calling empty()).
•
The Boost.Function code is now generated entirely by the Preprocessor library, so it is now possible to generate boost::function and boost::functionN class templates for any number of arguments.
•
The boost::bad_function_call exception class was introduced.
•
Version 1.29.0
: Boost.Function has been partially redesigned to minimize the interface and make it cleaner. Several seldom- or never-used features of the older Boost.Function have been deprecated and will be removed in the near future. Here is a list of features that have been deprecated, the likely impact of the deprecations, and how to adjust your code:

•
The boost::function class template syntax has changed. The old syntax, e.g., boost::function<int, float, double, std::string>, has been changed to a more natural syntax boost::function<int (float, double, std::string)>, where all return and argument types are encoded in a single function type parameter. Any other template parameters (e.g., the Allocator) follow this single parameter.
The resolution to this change depends on the abilities of your compiler: if your compiler supports template partial specialization and can parse function types (most do), modify your code to use the newer syntax (preferable) or directly use one of the functionN classes whose syntax has not changed. If your compiler does not support template partial specialization or function types, you must take the latter option and use the numbered Boost.Function classes. This option merely requires changing types such as boost::function<void, int, int> to boost::function2<void, int, int> (adding the number of function arguments to the end of the class name).
Support for the old syntax with the boost::function class template will persist for a short while, but will eventually be removed so that we can provide better error messages and link compatibility.
•
The invocation policy template parameter (Policy) has been deprecated and will be removed. There is no direct equivalent to this rarely used feature.
•
The mixin template parameter (Mixin) has been deprecated and will be removed. There is not direct equivalent to this rarely used feature.
•
The set methods have been deprecated and will be removed. Use the assignment operator instead.
Tutorial
Tutorial
Boost.Function has two syntactical forms: the preferred form and the portable form. The preferred form fits more closely with the C++ language and reduces the number of separate template parameters that need to be considered, often improving readability; however, the preferred form is not supported on all platforms due to compiler bugs. The compatible form will work on all compilers supported by Boost.Function. Consult the table below to determine which syntactic form to use for your compiler.

Preferred syntax
Portable syntax
•
GNU C++ 2.95.x, 3.0.x, 3.1.x
•
Comeau C++ 4.2.45.2
•
SGI MIPSpro 7.3.0
•
Intel C++ 5.0, 6.0
•
Compaq's cxx 6.2
•
Microsoft Visual C++ 7.1
•
Any compiler supporting the preferred syntax
•
Microsoft Visual C++ 6.0, 7.0
•
Borland C++ 5.5.1
•
Sun WorkShop 6 update 2 C++ 5.3
•
Metrowerks CodeWarrior 8.1

If your compiler does not appear in this list, please try the preferred syntax and report your results to the Boost list so that we can keep this table up-to-date.
Basic Usage
A function wrapper is defined simply by instantiating the function class template with the desired return type and argument types, formulated as a C++ function type. Any number of arguments may be supplied, up to some implementation-defined limit (10 is the default maximum). The following declares a function object wrapper f that takes two int parameters and returns a float:

Preferred syntax
Portable syntax
boost::function
<float (int x, int y)> f;
boost::function2
<float, int, int> f;

By default, function object wrappers are empty, so we can create a function object to assign to f:

struct int_div { float operator()(int x, int y) const { return ((float)x)/y; }; };
f = int_div();
Now we can use f to execute the underlying function object int_div:

std::cout << f(5, 3) << std::endl;
We are free to assign any compatible function object to f. If int_div had been declared to take two long operands, the implicit conversions would have been applied to the arguments without any user interference. The only limit on the types of arguments is that they be CopyConstructible, so we can even use references and arrays:

Preferred syntax
boost::function
<void (int values[], int n, int& sum, float& avg)> sum_avg;

Portable syntax
boost::function4
<void, int*, int, int&, float&> sum_avg;

void do_sum_avg(int values[], int n, int& sum, float& avg) { sum = 0; for (int i = 0; i < n; i++) sum += values[i]; avg = (float)sum / n; }
sum_avg = &do_sum_avg;
Invoking a function object wrapper that does not actually contain a function object is a precondition violation, much like trying to call through a null function pointer, and will throw a bad_function_call exception). We can check for an empty function object wrapper by using it in a boolean context (it evaluates true if the wrapper is not empty) or compare it against 0. For instance: if (f) std::cout << f(5, 3) << std::endl; else std::cout << "f has no target, so it is unsafe to call" << std::endl;
Alternatively, empty() method will return whether or not the wrapper is empty.
Finally, we can clear out a function target by assigning it to 0 or by calling the clear() member function, e.g., f = 0;
Free functions
Free function pointers can be considered singleton function objects with const function call operators, and can therefore be directly used with the function object wrappers: float mul_ints(int x, int y) { return ((float)x) * y; }f = &mul_ints;
Note that the & isn't really necessary unless you happen to be using Microsoft Visual C++ version 6.
Member functions
In many systems, callbacks often call to member functions of a particular object. This is often referred to as "argument binding", and is beyond the scope of Boost.Function. The use of member functions directly, however, is supported, so the following code is valid:

struct X { int foo(int); };

Preferred syntax
Portable syntax
boost::function
<int (X*, int)> f;

f = &X::foo;

X x; f(&x, 5);
boost::function2
<int, X*, int> f;

f = &X::foo;

X x; f(&x, 5);

Several libraries exist that support argument binding. Three such libraries are summarized below: •Bind. This library allows binding of arguments for any function object. It is lightweight and very portable.•The C++ Standard library. Using std::bind1st and std::mem_fun together one can bind the object of a pointer-to-member function for use with Boost.Function:

Preferred syntax
Portable syntax
boost::function
<int (int)> f; X x; f = std::bind1st( std::mem_fun(&X::foo), &x); f(5); // Call x.foo(5)
boost::function1
<int, int> f; X x; f = std::bind1st( std::mem_fun(&X::foo), &x); f(5); // Call x.foo(5)

•The Lambda library. This library provides a powerful composition mechanism to construct function objects that uses very natural C++ syntax. Lambda requires a compiler that is reasonably conformant to the C++ standard.
References to Function Objects
In some cases it is expensive (or semantically incorrect) to have Boost.Function clone a function object. In such cases, it is possible to request that Boost.Function keep only a reference to the actual function object. This is done using the ref and cref functions to wrap a reference to a function object:

Preferred syntax
Portable syntax
stateful_type a_function_object; boost::function<int (int)> f; f = boost::ref(a_function_object);

boost::function
<int (int)> f2(f);
stateful_type a_function_object; boost::function1<int, int> f; f = boost::ref(a_function_object);

boost::function1
<int, int> f2(f);

Here, f will not make a copy of a_function_object, nor will f2 when it is targeted to f's reference to a_function_object. Additionally, when using references to function objects, Boost.Function will not throw exceptions during assignment or construction.
Comparing Boost.Function function objects
Function object wrappers can be compared via == or != against any function object that can be stored within the wrapper. If the function object wrapper contains a function object of that type, it will be compared against the given function object (which must be EqualityComparable). For instance:
int compute_with_X(X*, int);

f = &X::foo; assert(f == &X::foo); assert(&compute_with_X != f);
When comparing against an instance of reference_wrapper, the address of the object in the reference_wrapper is compared against the address of the object stored by the function object wrapper:
a_stateful_object so1, so2; f = boost::ref(so1); assert(f == boost::ref(so1)); assert(f == so1); // Only if a_stateful_object is EqualityComparable assert(f != boost::ref(so2));
Reference
Reference
Definitions
•
A function object f is compatible if for the given set of argument types Arg1, Arg2, ..., ArgN and a return type ResultType, the appropriate following function is well-formed: // if ResultType is not void ResultType foo(Arg1 arg1, Arg2 arg2, ..., ArgN argN) { return f(arg1, arg2, ..., argN); } // if ResultType is void ResultType foo(Arg1 arg1, Arg2 arg2, ..., ArgN argN) { f(arg1, arg2, ..., argN); }
A special provision is made for pointers to member functions. Though they are not function objects, Boost.Function will adapt them internally to function objects. This requires that a pointer to member function of the form R (X::*mf)(Arg1, Arg2, ..., ArgN) cv-quals be adapted to a function object with the following function call operator overloads: template<typename P> R operator()(cv-quals P& x, Arg1 arg1, Arg2 arg2, ..., ArgN argN) const { return (*x).*mf(arg1, arg2, ..., argN); }
•
A function object f of type F is stateless if it is a function pointer or if boost::is_stateless<T> is true. The construction of or copy to a Boost.Function object from a stateless function object will not cause exceptions to be thrown and will not allocate any storage.
Header <boost/function.hpp>
namespace
boost { class bad_function_call; class function_base; template<typename R, typename T1, typename T2, ..., typename TN, typename Allocator = std::allocator<void> > class functionN; template<typename T1, typename T2, ..., typename TN, typename Allocator> void swap(functionN<T1, T2, ..., TN, Allocator>&, functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>&, Functor); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(Functor, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>&, reference_wrapper<Functor>); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor>, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator==(const functionN<T1, T2, ..., TN, Allocator1>&, const functionN<U1, U2, ..., UN, Allocator2>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>&, Functor); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(Functor, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>&, reference_wrapper<Functor>); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor>, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator!=(const functionN<T1, T2, ..., TN, Allocator1>&, const functionN<U1, U2, ..., UN, Allocator2>&); template<typename Signature, typename Allocator = std::allocator<void> > class function; template<typename Signature, typename Allocator> void swap(function<Signature, Allocator>&, function<Signature, Allocator>&); template<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>&, Functor); template<typename Signature, typename Allocator, typename Functor> bool operator==(Functor, const function<Signature, Allocator>&); template<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>&, reference_wrapper<Functor>); template<typename Signature, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor>, const function<Signature, Allocator>&); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator==(const function<Signature1, Allocator1>&, const function<Signature2, Allocator2>&); template<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>&, Functor); template<typename Signature, typename Allocator, typename Functor> bool operator!=(Functor, const function<Signature, Allocator>&); template<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>&, reference_wrapper<Functor>); template<typename Signature, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor>, const function<Signature, Allocator>&); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator!=(const function<Signature1, Allocator1>&, const function<Signature2, Allocator2>&); }
Class bad_function_call
Class bad_function_call -- An exception type thrown when an instance of a function object is empty when invoked.
boost::bad_function_call
class
bad_function_call : public std::runtime_error { public: // construct/copy/destruct bad_function_call(); };
Description
Description
bad_function_call construct/copy/destruct
bad_function_call
construct/copy/destruct
1.
bad_function_call();
Effects
Constructs a bad_function_call exception object.
Class function_base
Class function_base -- The common base class for all Boost.Function objects. Objects of type function_base may not be created directly.
boost::function_base
class
function_base { public:

// capacity
bool
empty
() const;

// target access
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const; template<typename Functor> bool contains(const Functor&) const; };
Description
Description
function_base capacity
function_base
capacity
1.
bool
empty() const;
Returns
false
if this has a target, and true otherwise.
Throws
Will not throw.
function_base target access
function_base
target access
1.
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const;
Returns
If this stores a target of type Functor, returns the address of the target. Otherwise, returns the NULL pointer.
Throws
Will not throw.
2.
template
<typename Functor> bool contains(const Functor& f) const;
Returns
true
if this->target<Functor>() is non-NULL and function_equal(*(this->target<Functor>()), f)
Class template functionN
Class template functionN -- A set of generalized function pointers that can be used for callbacks or wrapping function objects.
boost::functionN
template
<typename R, typename T1, typename T2, ..., typename TN, typename Allocator = std::allocator<void> > class functionN : public function_base { public: // types typedef R result_type; typedef Allocator allocator_type; typedef T1 argument_type; // If N == 1 typedef T1 first_argument_type; // If N == 2 typedef T2 second_argument_type; // If N == 2 typedef T1 arg1_type; typedef T2 arg2_type; . . . typedef TN argN_type;

// static constants
static
const
int
arity = N;

// Lambda library support
template
<typename Args> struct sig { // types typedef result_type type; };

// construct/copy/destruct
functionN
(); functionN(const functionN&); template<typename F> functionN(F); functionN& operator=(const functionN&); ~functionN();

// modifiers
void
swap
(const functionN&); void clear();

// capacity
bool
empty
() const; operator safe_bool() const; bool operator!() const;

// target access
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const; template<typename Functor> bool contains(const Functor&) const;

// invocation
result_type operator()(arg1_type, arg2_type, ..., argN_type) const; };

// specialized algorithms
template
<typename T1, typename T2, ..., typename TN, typename Allocator> void swap(functionN<T1, T2, ..., TN, Allocator>&, functionN<T1, T2, ..., TN, Allocator>&);

// comparison operators
template
<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>&, Functor); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(Functor, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>&, reference_wrapper<Functor>); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor>, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator==(const functionN<T1, T2, ..., TN, Allocator1>&, const functionN<U1, U2, ..., UN, Allocator2>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>&, Functor); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(Functor, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>&, reference_wrapper<Functor>); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor>, const functionN<T1, T2, ..., TN, Allocator>&); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator!=(const functionN<T1, T2, ..., TN, Allocator1>&, const functionN<U1, U2, ..., UN, Allocator2>&);
Description
Description
Class template functionN is actually a family of related classes function0, function1, etc., up to some implementation-defined maximum. In this context, N refers to the number of parameters.
functionN construct/copy/destruct
functionN
construct/copy/destruct
1.
functionN();
Postconditions
this->empty()
Throws
Will not throw.
2.
functionN(const functionN& f);
Postconditions
Contains a copy of the f's target, if it has one, or is empty if f.empty().
Throws
Will not throw unless copying the target of f throws.
3.
template
<typename F> functionN(F f);
Requires
F is a function object Callable from this.
Postconditions
*this
targets a copy of f if f is nonempty, or this->empty() if f is empty.
Throws
Will not throw when f is a stateless function object.
4.
functionN& operator=(const functionN& f);
Postconditions
*this
targets a copy of f's target, if it has one, or is empty if f.empty().
Throws
Will not throw when the target of f is a stateless function object or a reference to the function object.
5.
~functionN();
Effects
If !this->empty(), destroys the target of this.
functionN modifiers
functionN
modifiers
1.
void
swap(const functionN& f);
Effects
Interchanges the targets of *this and f.
Throws
Will not throw.
2.
void
clear();
Postconditions
this->empty()
Throws
Will not throw.
functionN capacity
functionN
capacity
1.
bool
empty() const;
Returns
false
if this has a target, and true otherwise.
Throws
Will not throw.
2.
operator
safe_bool() const;
Returns
A safe_bool that evaluates false in a boolean context when this->empty(), and true otherwise.
Throws
Will not throw.
3.
bool
operator
!() const;
Returns
this->empty()
Throws
Will not throw.
functionN target access
functionN
target access
1.
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const;
Returns
If this stores a target of type Functor, returns the address of the target. Otherwise, returns the NULL pointer.
Throws
Will not throw.
2.
template
<typename Functor> bool contains(const Functor& f) const;
Returns
true
if this->target<Functor>() is non-NULL and function_equal(*(this->target<Functor>()), f)
functionN invocation
functionN
invocation
1.
result_type operator()(arg1_type a1, arg2_type a2, ... , argN_type aN) const;
Effects
f(a1, a2, ..., aN)
, where f is the target of *this.
Returns
if R is void, nothing is returned; otherwise, the return value of the call to f is returned.
Throws
bad_function_call
if !this->empty(). Otherwise, may through any exception thrown by the target function f.
functionN specialized algorithms
functionN
specialized algorithms
1.
template
<typename T1, typename T2, ..., typename TN, typename Allocator> void swap(functionN<T1, T2, ..., TN, Allocator>& f1, functionN<T1, T2, ..., TN, Allocator>& f2);
Effects
f1.swap(f2)
Throws
Will not throw.
functionN comparison operators
functionN
comparison operators
1.
template
<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>& f, Functor g); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(Functor g, const functionN<T1, T2, ..., TN, Allocator>& f); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(const functionN<T1, T2, ..., TN, Allocator>& f, reference_wrapper<Functor> g); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor> g, const functionN<T1, T2, ..., TN, Allocator>& f); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator==(const functionN<T1, T2, ..., TN, Allocator1>& f1, const functionN<U1, U2, ..., UN, Allocator2>& f2);
Returns
True when f stores an object of type Functor and one of the following conditions applies: •g is of type reference_wrapper<Functor> and f.target<Functor>() == g.get_pointer().•g is not of type reference_wrapper<Functor> and function_equal(*(f.target<Functor>()), g).
Notes
functionN
objects are not EqualityComparable.
Rationale
The safe_bool conversion opens a loophole whereby two functionN instances can be compared via ==, although this is not feasible to implement. The undefined void operator== closes the loophole and ensures a compile-time or link-time error.
2.
template
<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>& f, Functor g); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(Functor g, const functionN<T1, T2, ..., TN, Allocator>& f); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(const functionN<T1, T2, ..., TN, Allocator>& f, reference_wrapper<Functor> g); template<typename T1, typename T2, ..., typename TN, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor> g, const functionN<T1, T2, ..., TN, Allocator>& f); template<typename T1, typename T2, ..., typename TN, typename Allocator1, typename U1, typename U2, ..., typename UN, typename Allocator2> void operator!=(const functionN<T1, T2, ..., TN, Allocator1>& f1, const functionN<U1, U2, ..., UN, Allocator2>& f2);
Returns
True when f does not store an object of type Functor or it stores an object of type Functor and one of the following conditions applies: •g is of type reference_wrapper<Functor> and f.target<Functor>() != g.get_pointer().•g is not of type reference_wrapper<Functor> and !function_equal(*(f.target<Functor>()), g).
Notes
functionN
objects are not EqualityComparable.
Rationale
The safe_bool conversion opens a loophole whereby two functionN instances can be compared via !=, although this is not feasible to implement. The undefined void operator!= closes the loophole and ensures a compile-time or link-time error.
Class template function
Class template function -- A generalized function pointer that can be used for callbacks or wrapping function objects.
boost::function
template
<typename Signature, // Function type R (T1, T2, ..., TN) typename Allocator = std::allocator<void> > class function : public functionN<R, T1, T2, ..., TN, Allocator> { public: // types typedef R result_type; typedef Allocator allocator_type; typedef T1 argument_type; // If N == 1 typedef T1 first_argument_type; // If N == 2 typedef T2 second_argument_type; // If N == 2 typedef T1 arg1_type; typedef T2 arg2_type; . . . typedef TN argN_type;

// static constants
static
const
int
arity = N;

// Lambda library support
template
<typename Args> struct sig { // types typedef result_type type; };

// construct/copy/destruct
function
(); function(const functionN&); function(const function&); template<typename F> function(F); function& operator=(const functionN&); function& operator=(const function&); ~function();

// modifiers
void
swap
(const function&); void clear();

// capacity
bool
empty
() const; operator safe_bool() const; bool operator!() const;

// target access
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const; template<typename Functor> bool contains(const Functor&) const;

// invocation
result_type operator()(arg1_type, arg2_type, ..., argN_type) const; };

// specialized algorithms
template
<typename Signature, typename Allocator> void swap(function<Signature, Allocator>&, function<Signature, Allocator>&);

// comparison operators
template
<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>&, Functor); template<typename Signature, typename Allocator, typename Functor> bool operator==(Functor, const function<Signature, Allocator>&); template<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>&, reference_wrapper<Functor>); template<typename Signature, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor>, const function<Signature, Allocator>&); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator==(const function<Signature1, Allocator1>&, const function<Signature2, Allocator2>&); template<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>&, Functor); template<typename Signature, typename Allocator, typename Functor> bool operator!=(Functor, const function<Signature, Allocator>&); template<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>&, reference_wrapper<Functor>); template<typename Signature, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor>, const function<Signature, Allocator>&); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator!=(const function<Signature1, Allocator1>&, const function<Signature2, Allocator2>&);
Description
Description
Class template function is a thin wrapper around the numbered class templates function0, function1, etc. It accepts a function type with N arguments and will will derive from functionN instantiated with the arguments it receives.
The semantics of all operations in class template function are equivalent to that of the underlying functionN object, although additional member functions are required to allow proper copy construction and copy assignment of function objects.
function construct/copy/destruct
function
construct/copy/destruct
1.
function();
Postconditions
this->empty()
Throws
Will not throw.
2.
function(const functionN& f);
Postconditions
Contains a copy of the f's target, if it has one, or is empty if f.empty().
Throws
Will not throw unless copying the target of f throws.
3.
function(const function& f);
Postconditions
Contains a copy of the f's target, if it has one, or is empty if f.empty().
Throws
Will not throw unless copying the target of f throws.
4.
template
<typename F> function(F f);
Requires
F is a function object Callable from this.
Postconditions
*this
targets a copy of f if f is nonempty, or this->empty() if f is empty.
Throws
Will not throw when f is a stateless function object.
5.
function& operator=(const functionN& f);
Postconditions
*this
targets a copy of f's target, if it has one, or is empty if f.empty()
Throws
Will not throw when the target of f is a stateless function object or a reference to the function object.
6.
function& operator=(const function& f);
Postconditions
*this
targets a copy of f's target, if it has one, or is empty if f.empty()
Throws
Will not throw when the target of f is a stateless function object or a reference to the function object.
7.
~function();
Effects
If !this->empty(), destroys the target of this.
function modifiers
function
modifiers
1.
void
swap(const function& f);
Effects
Interchanges the targets of *this and f.
Throws
Will not throw.
2.
void
clear();
Postconditions
this->empty()
Throws
Will not throw.
function capacity
function
capacity
1.
bool
empty() const;
Returns
false
if this has a target, and true otherwise.
Throws
Will not throw.
2.
operator
safe_bool() const;
Returns
A safe_bool that evaluates false in a boolean context when this->empty(), and true otherwise.
Throws
Will not throw.
3.
bool
operator
!() const;
Returns
this->empty()
Throws
Will not throw.
function target access
function
target access
1.
template
<typename Functor> Functor* target(); template<typename Functor> const Functor* target() const;
Returns
If this stores a target of type Functor, returns the address of the target. Otherwise, returns the NULL pointer.
Throws
Will not throw.
2.
template
<typename Functor> bool contains(const Functor& f) const;
Returns
true
if this->target<Functor>() is non-NULL and function_equal(*(this->target<Functor>()), f)
function invocation
function
invocation
1.
result_type operator()(arg1_type a1, arg2_type a2, ... , argN_type aN) const;
Effects
f(a1, a2, ..., aN)
, where f is the target of *this.
Returns
if R is void, nothing is returned; otherwise, the return value of the call to f is returned.
Throws
bad_function_call
if !this->empty(). Otherwise, may through any exception thrown by the target function f.
function specialized algorithms
function
specialized algorithms
1.
template
<typename Signature, typename Allocator> void swap(function<Signature, Allocator>& f1, function<Signature, Allocator>& f2);
Effects
f1.swap(f2)
Throws
Will not throw.
function comparison operators
function
comparison operators
1.
template
<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>& f, Functor g); template<typename Signature, typename Allocator, typename Functor> bool operator==(Functor g, const function<Signature, Allocator>& f); template<typename Signature, typename Allocator, typename Functor> bool operator==(const function<Signature, Allocator>& f, reference_wrapper<Functor> g); template<typename Signature, typename Allocator, typename Functor> bool operator==(reference_wrapper<Functor> g, const function<Signature, Allocator>& f); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator==(const function<Signature1, Allocator1>& f1, const function<Signature2, Allocator2>& f2);
Returns
True when f stores an object of type Functor and one of the following conditions applies: •g is of type reference_wrapper<Functor> and f.target<Functor>() == g.get_pointer().•g is not of type reference_wrapper<Functor> and function_equals(*(f.target<Functor>()), g).
Notes
function
objects are not EqualityComparable.
Rationale
The safe_bool conversion opens a loophole whereby two function instances can be compared via ==, although this is not feasible to implement. The undefined void operator== closes the loophole and ensures a compile-time or link-time error.
2.
template
<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>& f, Functor g); template<typename Signature, typename Allocator, typename Functor> bool operator!=(Functor g, const function<Signature, Allocator>& f); template<typename Signature, typename Allocator, typename Functor> bool operator!=(const function<Signature, Allocator>& f, reference_wrapper<Functor> g); template<typename Signature, typename Allocator, typename Functor> bool operator!=(reference_wrapper<Functor> g, const function<Signature, Allocator>& f); template<typename Signature1, typename Allocator1, typename Signature2, typename Allocator2> void operator!=(const function<Signature1, Allocator1>& f1, const function<Signature2, Allocator2>& f2);
Returns
True when f does not store an object of type Functor or it stores an object of type Functor and one of the following conditions applies: •g is of type reference_wrapper<Functor> and f.target<Functor>() != g.get_pointer().•g is not of type reference_wrapper<Functor> and !function_equals(*(f.target<Functor>()), g).
Notes
function
objects are not EqualityComparable.
Rationale
The safe_bool conversion opens a loophole whereby two function instances can be compared via !=, although this is not feasible to implement. The undefined void operator!= closes the loophole and ensures a compile-time or link-time error.
Header <boost/function_equal.hpp>
namespace
boost { template<typename F, typename G> bool function_equal(const F&, const G&); }
Function template function_equal
Function template function_equal -- Compare two function objects for equality.
boost::function_equal
template
<typename F, typename G> bool function_equal(const F& f, const G& g);
Description
Description
Returns
f == g
.
Throws
Only if f == g throws.
Frequently Asked Questions
Frequently Asked Questions
1.
Why can't I compare boost::function objects with operator== or operator!=?
Comparison between boost::function objects cannot be implemented "well", and therefore will not be implemented. The typical semantics requested for f == g given boost::function objects f and g are:
•
If f and g store function objects of the same type, use that type's operator== to compare them.
•
If f and g store function objects of different types, return false.
The problem occurs when the type of the function objects stored by both f and g doesn't have an operator==: we would like the expression f == g to fail to compile, as occurs with, e.g., the standard containers. However, this is not implementable for boost::function because it necessarily "erases" some type information after it has been assigned a function object, so it cannot try to call operator== later: it must either find a way to call operator== now, or it will never be able to call it later. Note, for instance, what happens if you try to put a float value into a boost::function object: you will get an error at the assignment operator or constructor, not in operator(), because the function-call expression must be bound in the constructor or assignment operator.
The most promising approach is to find a method of determining if operator== can be called for a particular type, and then supporting it only when it is available; in other situations, an exception would be thrown. However, to date there is no known way to detect if an arbitrary operator expression f == g is suitably defined. The best solution known has the following undesirable qualities:
1.
Fails at compile-time for objects where operator== is not accessible (e.g., because it is private).
2.
Fails at compile-time if calling operator== is ambiguous.
3.
Appears to be correct if the operator== declaration is correct, even though operator== may not compile.
All of these problems translate into failures in the boost::function constructors or assignment operator, even if the user never invokes operator==. We can't do that to users.
The other option is to place the burden on users that want to use operator==, e.g., by providing an is_equality_comparable trait they may specialize. This is a workable solution, but is dangerous in practice, because forgetting to specialize the trait will result in unexpected exceptions being thrown from boost::function's operator==. This essentially negates the usefulness of operator== in the context in which it is most desired: multitarget callbacks. The Signals library has a way around this.
2.
I see void pointers; is this [mess] type safe?
Yes, boost::function is type safe even though it uses void pointers and pointers to functions returning void and taking no arguments. Essentially, all type information is encoded in the functions that manage and invoke function pointers and function objects. Only these functions are instantiated with the exact type that is pointed to by the void pointer or pointer to void function. The reason that both are required is that one may cast between void pointers and object pointers safely or between different types of function pointers (provided you don't invoke a function pointer with the wrong type).
3.
Why are there workarounds for void returns? C++ allows them!
Void returns are permitted by the C++ standard, as in this code snippet: void f(); void g() { return f(); }
This is a valid usage of boost::function because void returns are not used. With void returns, we would attempting to compile ill-formed code similar to: int f(); void g() { return f(); }
In essence, not using void returns allows boost::function to swallow a return value. This is consistent with allowing the user to assign and invoke functions and function objects with parameters that don't exactly match.
4.
Why (function) cloning?
In November and December of 2000, the issue of cloning vs. reference counting was debated at length and it was decided that cloning gave more predictable semantics. I won't rehash the discussion here, but if it cloning is incorrect for a particular application a reference-counting allocator could be used.
5.
How much overhead does a call through boost::function incur?
The cost of boost::function can be reasonably consistently measured at around 20ns +/- 10 ns on a modern >2GHz platform versus directly inlining the code.
However, the performance of your application may benefit from or be disadvantaged by boost::function depending on how your C++ optimiser optimises. Similar to a standard function pointer, differences of order of 10% have been noted to the benefit or disadvantage of using boost::function to call a function that contains a tight loop depending on your compilation circumstances.
[Answer provided by Matt Hurd. See http://article.gmane.org/gmane.comp.lib.boost.devel/33278]
Miscellaneous Notes
Miscellaneous Notes
Boost.Function vs. Function Pointers
Boost.Function has several advantages over function pointers, namely:

•
Boost.Function allows arbitrary compatible function objects to be targets (instead of requiring an exact function signature).
•
Boost.Function may be used with argument-binding and other function object construction libraries.
•
Boost.Function has predictible behavior when an empty function object is called.
And, of course, function pointers have several advantages over Boost.Function:

•
Function pointers are smaller (the size of one pointer instead of three)
•
Function pointers are faster (Boost.Function may require two calls through function pointers)
•
Function pointers are backward-compatible with C libraries.
•
More readable error messages.
Performance
Function object wrapper size
Function object wrappers will be the size of two function pointers plus one function pointer or data pointer (whichever is larger). On common 32-bit platforms, this amounts to 12 bytes per wrapper. Additionally, the function object target will be allocated on the heap.
Copying efficiency
Copying function object wrappers may require allocating memory for a copy of the function object target. The default allocator may be replaced with a faster custom allocator or one may choose to allow the function object wrappers to only store function object targets by reference (using ref) if the cost of this cloning becomes prohibitive.
Invocation efficiency
With a properly inlining compiler, an invocation of a function object requires one call through a function pointer. If the call is to a free function pointer, an additional call must be made to that function pointer (unless the compiler has very powerful interprocedural analysis).
Combatting virtual function "bloat"
The use of virtual functions tends to cause 'code bloat' on many compilers. When a class contains a virtual function, it is necessary to emit an additional function that classifies the type of the object. It has been our experience that these auxiliary functions increase the size of the executable significantly when many boost::function objects are used.
In Boost.Function, an alternative but equivalent approach was taken using free functions instead of virtual functions. The Boost.Function object essentially holds two pointers to make a valid target call: a void pointer to the function object it contains and a void pointer to an "invoker" that can call the function object, given the function pointer. This invoker function performs the argument and return value conversions Boost.Function provides. A third pointer points to a free function called the "manager", which handles the cloning and destruction of function objects. The scheme is typesafe because the only functions that actually handle the function object, the invoker and the manager, are instantiated given the type of the function object, so they can safely cast the incoming void pointer (the function object pointer) to the appropriate type.
Acknowledgements
Many people were involved in the construction of this library. William Kempf, Jesse Jones and Karl Nelson were all extremely helpful in isolating an interface and scope for the library. John Maddock managed the formal review, and many reviewers gave excellent comments on interface, implementation, and documentation. Peter Dimov led us to the function declarator-based syntax.
Testsuite
Testsuite
Acceptance tests

Test
Type
Description
If failing...
function_test.cpp
run
Test the capabilities of the boost::function class template.
The boost::function class template may not be usable on your compiler. However, the library may still be usable via the boost::functionN class templates.
function_n_test.cpp
run
Test the capabilities of the boost::functionN class templates.
allocator_test.cpp
run
Test the use of custom allocators.
Allocators are ignored by the implementation.
stateless_test.cpp
run
Test the optimization of stateless function objects in the Boost.Function library.
The exception-safety and performance guarantees given for stateless function objects may not be met by the implementation.
lambda_test.cpp
run
Test the interaction between Boost.Function and Boost.Lambda.
Either Boost.Lambda does not work on the platform, or Boost.Function cannot safely be applied without the use of boost::unlambda.
contains_test.cpp
run
Test the operation of the target member function and the equality operators.
function_30.cpp
compile
Test the generation of a Boost.Function function object adaptor accepting 30 arguments.
The Boost.Function library may work for function object adaptors of up to 10 parameters, but will be unable to generate adaptors for an arbitrary number of parameters. Failure often indicates an error in the compiler's preprocessor.
function_arith_cxx98.cpp
run
Test the first tutorial example.
function_arith_portable.cpp
run
Test the first tutorial example.
sum_avg_cxx98.cpp
run
Test the second tutorial example.
sum_avg_portable.cpp
run
Test the second tutorial example.
mem_fun_cxx98.cpp
run
Test member function example from tutorial.
mem_fun_portable.cpp
run
Test member function example from tutorial.
std_bind_cxx98.cpp
run
Test standard binders example from tutorial.
std_bind_portable.cpp
run
Test standard binders example from tutorial.
function_ref_cxx98.cpp
run
Test boost::ref example from tutorial.
function_ref_portable.cpp
run
Test boost::ref example from tutorial.

Negative tests

Test
Type
Description
If failing...
function_test_fail1.cpp
compile-fail
Test the (incorrect!) use of comparisons between Boost.Function function objects.
Intuitive (but incorrect!) code may compile and will give meaningless results.
function_test_fail2.cpp
compile-fail
Test the use of an incompatible function object with Boost.Function
Incorrect code may compile (with potentially unexpected results).

Boost.Lambda

Boost.Lambda

Boost.Lambda
Jaakko Järvi <jarvi at cs tamu edu>
Copyright © 1999-2004 Jaakko JärviGary Powell
Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
In a nutshell
In a nutshell

The Boost Lambda Library (BLL in the sequel) is a C++ template library, which implements form of lambda abstractions for C++. The term originates from functional programming and lambda calculus, where a lambda abstraction defines an unnamed function. The primary motivation for the BLL is to provide flexible and convenient means to define unnamed function objects for STL algorithms. In explaining what the library is about, a line of code says more than a thousand words; the following line outputs the elements of some STL container a separated by spaces:

for_each(a.begin(), a.end(), std::cout << _1 << ' ');

The expression std::cout << _1 << ' ' defines a unary function object. The variable _1 is the parameter of this function, a placeholder for the actual argument. Within each iteration of for_each, the function is called with an element of a as the actual argument. This actual argument is substituted for the placeholder, and the “body” of the function is evaluated.
The essence of BLL is letting you define small unnamed function objects, such as the one above, directly on the call site of an STL algorithm.
Getting Started
Getting Started
Installing the library
The library consists of include files only, hence there is no installation procedure. The boost include directory must be on the include path. There are a number of include files that give different functionality:

•
lambda/lambda.hpp
defines lambda expressions for different C++ operators, see the section called “Operator expressions”.
•
lambda/bind.hpp
defines bind functions for up to 9 arguments, see the section called “Bind expressions”.
•
lambda/if.hpp
defines lambda function equivalents for if statements and the conditional operator, see the section called “Lambda expressions for control structures” (includes lambda.hpp).
•
lambda/loops.hpp
defines lambda function equivalent for looping constructs, see the section called “Lambda expressions for control structures”.
•
lambda/switch.hpp
defines lambda function equivalent for the switch statement, see the section called “Lambda expressions for control structures”.
•
lambda/construct.hpp
provides tools for writing lambda expressions with constructor, destructor, new and delete invocations, see the section called “Construction and destruction” (includes lambda.hpp).
•
lambda/casts.hpp
provides lambda versions of different casts, as well as sizeof and typeid, see the section called “ Cast expressions ”.
•
lambda/exceptions.hpp
gives tools for throwing and catching exceptions within lambda functions, the section called “Exceptions” (includes lambda.hpp).
•
lambda/algorithm.hpp
and lambda/numeric.hpp (cf. standard algortihm and numeric headers) allow nested STL algorithm invocations, see the section called “Nesting STL algorithm invocations”.

Any other header files in the package are for internal use. Additionally, the library depends on two other Boost Libraries, the Tuple[tuple] and the type_traits[type_traits] libraries, and on the boost/ref.hpp header.
All definitions are placed in the namespace boost::lambda and its subnamespaces.
Conventions used in this document
In most code examples, we omit the namespace prefixes for names in the std and boost::lambda namespaces. Implicit using declarations using namespace std; using namespace boost::lambda; are assumed to be in effect.
Introduction
Introduction
Motivation
The Standard Template Library (STL) [STL94], now part of the C++ Standard Library [C++98], is a generic container and algorithm library. Typically STL algorithms operate on container elements via function objects. These function objects are passed as arguments to the algorithms.
Any C++ construct that can be called with the function call syntax is a function object. The STL contains predefined function objects for some common cases (such as plus, less and not1). As an example, one possible implementation for the standard plus template is:

template <class T> : public binary_function<T, T, T> struct plus { T operator()(const T& i, const T& j) const { return i + j; } };

The base class binary_function<T, T, T> contains typedefs for the argument and return types of the function object, which are needed to make the function object adaptable.
In addition to the basic function object classes, such as the one above, the STL contains binder templates for creating a unary function object from an adaptable binary function object by fixing one of the arguments to a constant value. For example, instead of having to explicitly write a function object class like:

class plus_1 { int _i; public: plus_1(const int& i) : _i(i) {} int operator()(const int& j) { return _i + j; } };

the equivalent functionality can be achieved with the plus template and one of the binder templates (bind1st). E.g., the following two expressions create function objects with identical functionalities; when invoked, both return the result of adding 1 to the argument of the function object:

plus_1(1) bind1st(plus<int>(), 1)

The subexpression plus<int>() in the latter line is a binary function object which computes the sum of two integers, and bind1st invokes this function object partially binding the first argument to 1. As an example of using the above function object, the following code adds 1 to each element of some container a and outputs the results into the standard output stream cout.

transform(a.begin(), a.end(), ostream_iterator<int>(cout), bind1st(plus<int>(), 1));
To make the binder templates more generally applicable, the STL contains adaptors for making pointers or references to functions, and pointers to member functions, adaptable.

Finally, some STL implementations contain function composition operations as extensions to the standard [SGI02].
All these tools aim at one goal: to make it possible to specify unnamed functions in a call of an STL algorithm, in other words, to pass code fragments as an argument to a function.

However, this goal is attained only partially. The simple example above shows that the definition of unnamed functions with the standard tools is cumbersome.

Complex expressions involving functors, adaptors, binders and function composition operations tend to be difficult to comprehend.

In addition to this, there are significant restrictions in applying the standard tools. E.g. the standard binders allow only one argument of a binary function to be bound; there are no binders for 3-ary, 4-ary etc. functions.
The Boost Lambda Library provides solutions for the problems described above:

•
Unnamed functions can be created easily with an intuitive syntax.

The above example can be written as:

transform(a.begin(), a.end(), ostream_iterator<int>(cout), 1 + _1);

or even more intuitively:

for_each(a.begin(), a.end(), cout << (1 + _1));
•
Most of the restrictions in argument binding are removed, arbitrary arguments of practically any C++ function can be bound.
•
Separate function composition operations are not needed, as function composition is supported implicitly.

Introduction to lambda expressions
Lambda expression are common in functional programming languages. Their syntax varies between languages (and between different forms of lambda calculus), but the basic form of a lambda expressions is:

lambda x1 ... xn.e

A lambda expression defines an unnamed function and consists of: • the parameters of this function: x1 ... xn. •the expression e which computes the value of the function in terms of the parameters x1 ... xn.

A simple example of a lambda expression is lambda x y.x+y Applying the lambda function means substituting the formal parameters with the actual arguments: (lambda x y.x+y) 2 3 = 2 + 3 = 5
In the C++ version of lambda expressions the lambda x1 ... xn part is missing and the formal parameters have predefined names. In the current version of the library, there are three such predefined formal parameters, called placeholders: _1, _2 and _3. They refer to the first, second and third argument of the function defined by the lambda expression.

For example, the C++ version of the definition lambda x y.x+y is _1 + _2
Hence, there is no syntactic keyword for C++ lambda expressions. The use of a placeholder as an operand implies that the operator invocation is a lambda expression. However, this is true only for operator invocations. Lambda expressions containing function calls, control structures, casts etc. require special syntactic constructs. Most importantly, function calls need to be wrapped inside a bind function.

As an example, consider the lambda expression:

lambda x y.foo(x,y)

Rather than foo(_1, _2), the C++ counterpart for this expression is:

bind(foo, _1, _2)

We refer to this type of C++ lambda expressions as bind expressions.
A lambda expression defines a C++ function object, hence function application syntax is like calling any other function object, for instance: (_1 + _2)(i, j).

Partial function application
A bind expression is in effect a partial function application. In partial function application, some of the arguments of a function are bound to fixed values. The result is another function, with possibly fewer arguments. When called with the unbound arguments, this new function invokes the original function with the merged argument list of bound and unbound arguments.
Terminology
A lambda expression defines a function. A C++ lambda expression concretely constructs a function object, a functor, when evaluated. We use the name lambda functor to refer to such a function object. Hence, in the terminology adopted here, the result of evaluating a lambda expression is a lambda functor.
Using the library
Using the library
The purpose of this section is to introduce the basic functionality of the library. There are quite a lot of exceptions and special cases, but discussion of them is postponed until later sections.

Introductory Examples
In this section we give basic examples of using BLL lambda expressions in STL algorithm invocations. We start with some simple expressions and work up. First, we initialize the elements of a container, say, a list, to the value 1:

list<int> v(10); for_each(v.begin(), v.end(), _1 = 1);

The expression _1 = 1 creates a lambda functor which assigns the value 1 to every element in v. 1 1 Strictly taken, the C++ standard defines for_each as a non-modifying sequence operation, and the function object passed to for_each should not modify its argument. The requirements for the arguments of for_each are unnecessary strict, since as long as the iterators are mutable, for_each accepts a function object that can have side-effects on their argument. Nevertheless, it is straightforward to provide another function template with the functionality ofstd::for_each but more fine-grained requirements for its arguments.
Next, we create a container of pointers and make them point to the elements in the first container v:

vector<int*> vp(10); transform(v.begin(), v.end(), vp.begin(), &_1);

The expression &_1 creates a function object for getting the address of each element in v. The addresses get assigned to the corresponding elements in vp.
The next code fragment changes the values in v. For each element, the function foo is called. The original value of the element is passed as an argument to foo. The result of foo is assigned back to the element:

int foo(int); for_each(v.begin(), v.end(), _1 = bind(foo, _1));
The next step is to sort the elements of vp:

sort(vp.begin(), vp.end(), *_1 > *_2);

In this call to sort, we are sorting the elements by their contents in descending order.
Finally, the following for_each call outputs the sorted content of vp separated by line breaks:

for_each(vp.begin(), vp.end(), cout << *_1 << '\n');

Note that a normal (non-lambda) expression as subexpression of a lambda expression is evaluated immediately. This may cause surprises. For instance, if the previous example is rewritten as for_each(vp.begin(), vp.end(), cout << '\n' << *_1); the subexpression cout << '\n' is evaluated immediately and the effect is to output a single line break, followed by the elements of vp. The BLL provides functions constant and var to turn constants and, respectively, variables into lambda expressions, and can be used to prevent the immediate evaluation of subexpressions: for_each(vp.begin(), vp.end(), cout << constant('\n') << *_1); These functions are described more thoroughly in the section called “Delaying constants and variables”
Parameter and return types of lambda functors
During the invocation of a lambda functor, the actual arguments are substituted for the placeholders. The placeholders do not dictate the type of these actual arguments. The basic rule is that a lambda function can be called with arguments of any types, as long as the lambda expression with substitutions performed is a valid C++ expression. As an example, the expression _1 + _2 creates a binary lambda functor. It can be called with two objects of any types A and B for which operator+(A,B) is defined (and for which BLL knows the return type of the operator, see below).
C++ lacks a mechanism to query a type of an expression. However, this precise mechanism is crucial for the implementation of C++ lambda expressions. Consequently, BLL includes a somewhat complex type deduction system which uses a set of traits classes for deducing the resulting type of lambda functions. It handles expressions where the operands are of built-in types and many of the expressions with operands of standard library types. Many of the user defined types are covered as well, particularly if the user defined operators obey normal conventions in defining the return types.
There are, however, cases when the return type cannot be deduced. For example, suppose you have defined:

C operator+(A, B);

The following lambda function invocation fails, since the return type cannot be deduced:

A a; B b; (_1 + _2)(a, b);
There are two alternative solutions to this. The first is to extend the BLL type deduction system to cover your own types (see the section called “Extending return type deduction system”). The second is to use a special lambda expression (ret) which defines the return type in place (see the section called “Overriding the deduced return type”):

A a; B b; ret<C>(_1 + _2)(a, b);
For bind expressions, the return type can be defined as a template argument of the bind function as well: bind<int>(foo, _1, _2);
About actual arguments to lambda functors
A general restriction for the actual arguments is that they cannot be non-const rvalues. For example:

int i = 1; int j = 2; (_1 + _2)(i, j); // ok (_1 + _2)(1, 2); // error (!)

This restriction is not as bad as it may look. Since the lambda functors are most often called inside STL-algorithms, the arguments originate from dereferencing iterators and the dereferencing operators seldom return rvalues. And for the cases where they do, there are workarounds discussed in the section called “Rvalues as actual arguments to lambda functors”.

Storing bound arguments in lambda functions

By default, temporary const copies of the bound arguments are stored in the lambda functor.

This means that the value of a bound argument is fixed at the time of the creation of the lambda function and remains constant during the lifetime of the lambda function object. For example: int i = 1; (_1 = 2, _1 + i)(i); The comma operator is overloaded to combine lambda expressions into a sequence; the resulting unary lambda functor first assigns 2 to its argument, then adds the value of i to it. The value of the expression in the last line is 3, not 4. In other words, the lambda expression that is created is lambda x.(x = 2, x + 1) rather than lambda x.(x = 2, x + i).

As said, this is the default behavior for which there are exceptions. The exact rules are as follows:

•

The programmer can control the storing mechanism with ref and cref wrappers [ref].

Wrapping an argument with ref, or cref, instructs the library to store the argument as a reference, or as a reference to const respectively.

For example, if we rewrite the previous example and wrap the variable i with ref, we are creating the lambda expression lambda x.(x = 2, x + i) and the value of the expression in the last line will be 4:

i = 1; (_1 = 2, _1 + ref(i))(i);

Note that ref and cref are different from var and constant.

While the latter ones create lambda functors, the former do not. For example:

int i; var(i) = 1; // ok ref(i) = 1; // not ok, ref(i) is not a lambda functor

The functions ref and cref mostly exist for historical reasons, and ref can always be replaced with var, and cref with constant_ref. See the section called “Delaying constants and variables” for details. The ref and cref functions are general purpose utility functions in Boost, and hence defined directly in the boost namespace.

•
Array types cannot be copied, they are thus stored as const reference by default.
•
For some expressions it makes more sense to store the arguments as references.

For example, the obvious intention of the lambda expression i += _1 is that calls to the lambda functor affect the value of the variable i, rather than some temporary copy of it.

As another example, the streaming operators take their leftmost argument as non-const references.

The exact rules are:

•
The left argument of compound assignment operators (+=, *=, etc.) are stored as references to non-const.
•
If the left argument of << or >> operator is derived from an instantiation of basic_ostream or respectively from basic_istream, the argument is stored as a reference to non-const. For all other types, the argument is stored as a copy.
•
In pointer arithmetic expressions, non-const array types are stored as non-const references. This is to prevent pointer arithmetic making non-const arrays const.

Lambda expressions in details
Lambda expressions in details
This section describes different categories of lambda expressions in details. We devote a separate section for each of the possible forms of a lambda expression.

Placeholders
The BLL defines three placeholder types: placeholder1_type, placeholder2_type and placeholder3_type. BLL has a predefined placeholder variable for each placeholder type: _1, _2 and _3. However, the user is not forced to use these placeholders. It is easy to define placeholders with alternative names. This is done by defining new variables of placeholder types. For example:

boost::lambda::placeholder1_type X; boost::lambda::placeholder2_type Y; boost::lambda::placeholder3_type Z;

With these variables defined, X += Y * Z is equivalent to _1 += _2 * _3.
The use of placeholders in the lambda expression determines whether the resulting function is nullary, unary, binary or 3-ary. The highest placeholder index is decisive. For example:

_1 + 5 // unary _1 * _1 + _1 // unary _1 + _2 // binary bind(f, _1, _2, _3) // 3-ary _3 + 10 // 3-ary

Note that the last line creates a 3-ary function, which adds 10 to its third argument. The first two arguments are discarded. Furthermore, lambda functors only have a minimum arity. One can always provide more arguments (up the number of supported placeholders) that is really needed. The remaining arguments are just discarded. For example:

int i, j, k; _1(i, j, k) // returns i, discards j and k (_2 + _2)(i, j, k) // returns j+j, discards i and k

See the section called “ Lambda functor arity ” for the design rationale behind this functionality.

In addition to these three placeholder types, there is also a fourth placeholder type placeholderE_type. The use of this placeholder is defined in the section called “Exceptions” describing exception handling in lambda expressions.
When an actual argument is supplied for a placeholder, the parameter passing mode is always by reference. This means that any side-effects to the placeholder are reflected to the actual argument. For example:

int i = 1; (_1 += 2)(i); // i is now 3 (++_1, cout << _1)(i) // i is now 4, outputs 4
Operator expressions
The basic rule is that any C++ operator invocation with at least one argument being a lambda expression is itself a lambda expression. Almost all overloadable operators are supported. For example, the following is a valid lambda expression:

cout << _1, _2[_3] = _1 && false
However, there are some restrictions that originate from the C++ operator overloading rules, and some special cases.
Operators that cannot be overloaded
Some operators cannot be overloaded at all (::, ., .*). For some operators, the requirements on return types prevent them to be overloaded to create lambda functors. These operators are ->., ->, new, new[], delete, delete[] and ?: (the conditional operator).
Assignment and subscript operators
These operators must be implemented as class members. Consequently, the left operand must be a lambda expression. For example:

int i; _1 = i; // ok i = _1; // not ok. i is not a lambda expression

There is a simple solution around this limitation, described in the section called “Delaying constants and variables”. In short, the left hand argument can be explicitly turned into a lambda functor by wrapping it with a special var function: var(i) = _1; // ok
Logical operators
Logical operators obey the short-circuiting evaluation rules. For example, in the following code, i is never incremented: bool flag = true; int i = 0; (_1 || ++_2)(flag, i);
Comma operator
Comma operator is the “statement separator” in lambda expressions. Since comma is also the separator between arguments in a function call, extra parenthesis are sometimes needed:

for_each(a.begin(), a.end(), (++_1, cout << _1));

Without the extra parenthesis around ++_1, cout << _1, the code would be interpreted as an attempt to call for_each with four arguments.
The lambda functor created by the comma operator adheres to the C++ rule of always evaluating the left operand before the right one. In the above example, each element of a is first incremented, then written to the stream.
Function call operator
The function call operators have the effect of evaluating the lambda functor. Calls with too few arguments lead to a compile time error.
Member pointer operator
The member pointer operator operator->* can be overloaded freely. Hence, for user defined types, member pointer operator is no special case. The built-in meaning, however, is a somewhat more complicated case. The built-in member pointer operator is applied if the left argument is a pointer to an object of some class A, and the right hand argument is a pointer to a member of A, or a pointer to a member of a class from which A derives. We must separate two cases:

•
The right hand argument is a pointer to a data member. In this case the lambda functor simply performs the argument substitution and calls the built-in member pointer operator, which returns a reference to the member pointed to. For example: struct A { int d; }; A* a = new A(); ... (a ->* &A::d); // returns a reference to a->d (_1 ->* &A::d)(a); // likewise
•
The right hand argument is a pointer to a member function. For a built-in call like this, the result is kind of a delayed member function call. Such an expression must be followed by a function argument list, with which the delayed member function call is performed. For example: struct B { int foo(int); }; B* b = new B(); ... (b ->* &B::foo) // returns a delayed call to b->foo // a function argument list must follow (b ->* &B::foo)(1) // ok, calls b->foo(1) (_1 ->* &B::foo)(b); // returns a delayed call to b->foo, // no effect as such (_1 ->* &B::foo)(b)(1); // calls b->foo(1)
Bind expressions
Bind expressions can have two forms:

bind(target-function, bind-argument-list) bind(target-member-function, object-argument, bind-argument-list)

A bind expression delays the call of a function. If this target function is n-ary, then the bind-argument-list must contain n arguments as well. In the current version of the BLL, 0 <= n <= 9 must hold. For member functions, the number of arguments must be at most 8, as the object argument takes one argument position.

Basically, the bind-argument-list must be a valid argument list for the target function, except that any argument can be replaced with a placeholder, or more generally, with a lambda expression. Note that also the target function can be a lambda expression.

The result of a bind expression is either a nullary, unary, binary or 3-ary function object depending on the use of placeholders in the bind-argument-list (see the section called “Placeholders”).
The return type of the lambda functor created by the bind expression can be given as an explicitly specified template parameter, as in the following example: bind<RET>(target-function, bind-argument-list) This is only necessary if the return type of the target function cannot be deduced.
The following sections describe the different types of bind expressions.
Function pointers or references as targets
The target function can be a pointer or a reference to a function and it can be either bound or unbound. For example: X foo(A, B, C); A a; B b; C c; bind(foo, _1, _2, c)(a, b); bind(&foo, _1, _2, c)(a, b); bind(_1, a, b, c)(foo);

The return type deduction always succeeds with this type of bind expressions.
Note, that in C++ it is possible to take the address of an overloaded function only if the address is assigned to, or used as an initializer of, a variable, the type of which solves the amibiguity, or if an explicit cast expression is used. This means that overloaded functions cannot be used in bind expressions directly, e.g.: void foo(int); void foo(float); int i; ... bind(&foo, _1)(i); // error ... void (*pf1)(int) = &foo; bind(pf1, _1)(i); // ok bind(static_cast<void(*)(int)>(&foo), _1)(i); // ok
Member functions as targets
The syntax for using pointers to member function in bind expression is: bind(target-member-function, object-argument, bind-argument-list)

The object argument can be a reference or pointer to the object, the BLL supports both cases with a uniform interface:

bool A::foo(int) const; A a; vector<int> ints; ... find_if(ints.begin(), ints.end(), bind(&A::foo, a, _1)); find_if(ints.begin(), ints.end(), bind(&A::foo, &a, _1));

Similarly, if the object argument is unbound, the resulting lambda functor can be called both via a pointer or a reference:

bool A::foo(int); list<A> refs; list<A*> pointers; ... find_if(refs.begin(), refs.end(), bind(&A::foo, _1, 1)); find_if(pointers.begin(), pointers.end(), bind(&A::foo, _1, 1));
Even though the interfaces are the same, there are important semantic differences between using a pointer or a reference as the object argument. The differences stem from the way bind-functions take their parameters, and how the bound parameters are stored within the lambda functor. The object argument has the same parameter passing and storing mechanism as any other bind argument slot (see the section called “Storing bound arguments in lambda functions”); it is passed as a const reference and stored as a const copy in the lambda functor. This creates some asymmetry between the lambda functor and the original member function, and between seemingly similar lambda functors. For example: class A { int i; mutable int j; public: A(int ii, int jj) : i(ii), j(jj) {}; void set_i(int x) { i = x; }; void set_j(int x) const { j = x; }; };

When a pointer is used, the behavior is what the programmer might expect:

A a(0,0); int k = 1; bind(&A::set_i, &a, _1)(k); // a.i == 1 bind(&A::set_j, &a, _1)(k); // a.j == 1

Even though a const copy of the object argument is stored, the original object a is still modified. This is since the object argument is a pointer, and the pointer is copied, not the object it points to. When we use a reference, the behaviour is different:

A a(0,0); int k = 1; bind(&A::set_i, a, _1)(k); // error; a const copy of a is stored. // Cannot call a non-const function set_i bind(&A::set_j, a, _1)(k); // a.j == 0, as a copy of a is modified
To prevent the copying from taking place, one can use the ref or cref wrappers (var and constant_ref would do as well): bind(&A::set_i, ref(a), _1)(k); // a.j == 1 bind(&A::set_j, cref(a), _1)(k); // a.j == 1
Note that the preceding discussion is relevant only for bound arguments. If the object argument is unbound, the parameter passing mode is always by reference. Hence, the argument a is not copied in the calls to the two lambda functors below: A a(0,0); bind(&A::set_i, _1, 1)(a); // a.i == 1 bind(&A::set_j, _1, 1)(a); // a.j == 1
Member variables as targets
A pointer to a member variable is not really a function, but the first argument to the bind function can nevertheless be a pointer to a member variable. Invoking such a bind expression returns a reference to the data member. For example:

struct A { int data; }; A a; bind(&A::data, _1)(a) = 1; // a.data == 1

The cv-qualifiers of the object whose member is accessed are respected. For example, the following tries to write into a const location: const A ca = a; bind(&A::data, _1)(ca) = 1; // error
Function objects as targets

Function objects, that is, class objects which have the function call operator defined, can be used as target functions.

In general, BLL cannot deduce the return type of an arbitrary function object.

However, there are two methods for giving BLL this capability for a certain function object class.

The result_type typedef

The BLL supports the standard library convention of declaring the return type of a function object with a member typedef named result_type in the function object class.

Here is a simple example: struct A { typedef B result_type; B operator()(X, Y, Z); };

If a function object does not define a result_type typedef, the method described below (sig template) is attempted to resolve the return type of the function object. If a function object defines both result_type and sig, result_type takes precedence.

The sig template
Another mechanism that make BLL aware of the return type(s) of a function object is defining member template struct sig<Args> with a typedef type that specifies the return type.

Here is a simple example: struct A { template <class Args> struct sig { typedef B type; } B operator()(X, Y, Z); };

The template argument Args is a tuple (or more precisely a cons list) type [tuple], where the first element is the function object type itself, and the remaining elements are the types of the arguments, with which the function object is being called.

This may seem overly complex compared to defining the result_type typedef. Howver, there are two significant restrictions with using just a simple typedef to express the return type: 1. If the function object defines several function call operators, there is no way to specify different result types for them. 2. If the function call operator is a template, the result type may depend on the template parameters. Hence, the typedef ought to be a template too, which the C++ language does not support.

The following code shows an example, where the return type depends on the type of one of the arguments, and how that dependency can be expressed with the sig template:

struct A {

// the return type equals the third argument type: template<class T1, class T2, class T3> T3 operator()(const T1& t1, const T2& t2, const T3& t3) const;

template <class Args> class sig { // get the third argument type (4th element) typedef typename boost::tuples::element<3, Args>::type T3; public: typedef typename boost::remove_cv<T3>::type type; }; };

The elements of the Args tuple are always non-reference types.

Moreover, the element types can have a const or volatile qualifier (jointly referred to as cv-qualifiers), or both. This is since the cv-qualifiers in the arguments can affect the return type. The reason for including the potentially cv-qualified function object type itself into the Args tuple, is that the function object class can contain both const and non-const (or volatile, even const volatile) function call operators, and they can each have a different return type.
The sig template can be seen as a meta-function that maps the argument type tuple to the result type of the call made with arguments of the types in the tuple.

As the example above demonstrates, the template can end up being somewhat complex. Typical tasks to be performed are the extraction of the relevant types from the tuple, removing cv-qualifiers etc. See the Boost type_traits [type_traits] and Tuple [type_traits] libraries for tools that can aid in these tasks. The sig templates are a refined version of a similar mechanism first introduced in the FC++ library [fc++].
Overriding the deduced return type
The return type deduction system may not be able to deduce the return types of some user defined operators or bind expressions with class objects.

A special lambda expression type is provided for stating the return type explicitly and overriding the deduction system. To state that the return type of the lambda functor defined by the lambda expression e is T, you can write:

ret<T>(e);

The effect is that the return type deduction is not performed for the lambda expression e at all, but instead, T is used as the return type. Obviously T cannot be an arbitrary type, the true result of the lambda functor must be implicitly convertible to T. For example:

A a; B b; C operator+(A, B); int operator*(A, B); ... ret<D>(_1 + _2)(a, b); // error (C cannot be converted to D) ret<C>(_1 + _2)(a, b); // ok ret<float>(_1 * _2)(a, b); // ok (int can be converted to float) ... struct X { Y operator(int)(); }; ... X x; int i; bind(x, _1)(i); // error, return type cannot be deduced ret<Y>(bind(x, _1))(i); // ok
For bind expressions, there is a short-hand notation that can be used instead of ret. The last line could alternatively be written as:

bind<Z>(x, _1)(i);
This feature is modeled after the Boost Bind library [bind].

Note that within nested lambda expressions, the ret must be used at each subexpression where the deduction would otherwise fail. For example: A a; B b; C operator+(A, B); D operator-(C); ... ret<D>( - (_1 + _2))(a, b); // error ret<D>( - ret<C>(_1 + _2))(a, b); // ok
If you find yourself using ret repeatedly with the same types, it is worth while extending the return type deduction (see the section called “Extending return type deduction system”).
Nullary lambda functors and ret
As stated above, the effect of ret is to prevent the return type deduction to be performed. However, there is an exception. Due to the way the C++ template instantiation works, the compiler is always forced to instantiate the return type deduction templates for zero-argument lambda functors. This introduces a slight problem with ret, best described with an example:

struct F { int operator()(int i) const; }; F f; ... bind(f, _1); // fails, cannot deduce the return type ret<int>(bind(f, _1)); // ok ... bind(f, 1); // fails, cannot deduce the return type ret<int>(bind(f, 1)); // fails as well!
The BLL cannot deduce the return types of the above bind calls, as F does not define the typedef result_type. One would expect ret to fix this, but for the nullary lambda functor that results from a bind expression (last line above) this does not work. The return type deduction templates are instantiated, even though it would not be necessary and the result is a compilation error.
The solution to this is not to use the ret function, but rather define the return type as an explicitly specified template parameter in the bind call: bind<int>(f, 1); // ok

The lambda functors created with ret<T>(bind(arg-list)) and bind<T>(arg-list) have the exact same functionality — apart from the fact that for some nullary lambda functors the former does not work while the latter does.
Delaying constants and variables
The unary functions constant, constant_ref and var turn their argument into a lambda functor, that implements an identity mapping. The former two are for constants, the latter for variables. The use of these delayed constants and variables is sometimes necessary due to the lack of explicit syntax for lambda expressions. For example: for_each(a.begin(), a.end(), cout << _1 << ' '); for_each(a.begin(), a.end(), cout << ' ' << _1); The first line outputs the elements of a separated by spaces, while the second line outputs a space followed by the elements of a without any separators. The reason for this is that neither of the operands of cout << ' ' is a lambda expression, hence cout << ' ' is evaluated immediately.

To delay the evaluation of cout << ' ', one of the operands must be explicitly marked as a lambda expression. This is accomplished with the constant function: for_each(a.begin(), a.end(), cout << constant(' ') << _1);

The call constant(' ') creates a nullary lambda functor which stores the character constant ' ' and returns a reference to it when invoked. The function constant_ref is similar, except that it stores a constant reference to its argument.

The constant and consant_ref are only needed when the operator call has side effects, like in the above example.
Sometimes we need to delay the evaluation of a variable. Suppose we wanted to output the elements of a container in a numbered list:

int index = 0; for_each(a.begin(), a.end(), cout << ++index << ':' << _1 << '\n'); for_each(a.begin(), a.end(), cout << ++var(index) << ':' << _1 << '\n');

The first for_each invocation does not do what we want; index is incremented only once, and its value is written into the output stream only once. By using var to make index a lambda expression, we get the desired effect.
In sum, var(x) creates a nullary lambda functor, which stores a reference to the variable x. When the lambda functor is invoked, a reference to x is returned.
Naming delayed constants and variables
It is possible to predefine and name a delayed variable or constant outside a lambda expression. The templates var_type, constant_type and constant_ref_type serve for this purpose. They are used as: var_type<T>::type delayed_i(var(i)); constant_type<T>::type delayed_c(constant(c)); The first line defines the variable delayed_i which is a delayed version of the variable i of type T. Analogously, the second line defines the constant delayed_c as a delayed version of the constant c. For example:

int i = 0; int j; for_each(a.begin(), a.end(), (var(j) = _1, _1 = var(i), var(i) = var(j)));
is equivalent to: int i = 0; int j; var_type<int>::type vi(var(i)), vj(var(j)); for_each(a.begin(), a.end(), (vj = _1, _1 = vi, vi = vj));
Here is an example of naming a delayed constant: constant_type<char>::type space(constant(' ')); for_each(a.begin(),a.end(), cout << space << _1);
About assignment and subscript operators
As described in the section called “Assignment and subscript operators”, assignment and subscripting operators are always defined as member functions. This means, that for expressions of the form x = y or x[y] to be interpreted as lambda expressions, the left-hand operand x must be a lambda expression. Consequently, it is sometimes necessary to use var for this purpose. We repeat the example from the section called “Assignment and subscript operators”:

int i; i = _1; // error var(i) = _1; // ok

Note that the compound assignment operators +=, -= etc. can be defined as non-member functions, and thus they are interpreted as lambda expressions even if only the right-hand operand is a lambda expression. Nevertheless, it is perfectly ok to delay the left operand explicitly. For example, i += _1 is equivalent to var(i) += _1.
Lambda expressions for control structures
BLL defines several functions to create lambda functors that represent control structures. They all take lambda functors as parameters and return void. To start with an example, the following code outputs all even elements of some container a:

for_each(a.begin(), a.end(), if_then(_1 % 2 == 0, cout << _1));
The BLL supports the following function templates for control structures:

if_then(condition, then_part) if_then_else(condition, then_part, else_part) if_then_else_return(condition, then_part, else_part) while_loop(condition, body) while_loop(condition) // no body case do_while_loop(condition, body) do_while_loop(condition) // no body case for_loop(init, condition, increment, body) for_loop(init, condition, increment) // no body case switch_statement(...)

The return types of all control construct lambda functor is void, except for if_then_else_return, which wraps a call to the conditional operator condition ? then_part : else_part The return type rules for this operator are somewhat complex. Basically, if the branches have the same type, this type is the return type. If the type of the branches differ, one branch, say of type A, must be convertible to the other branch, say of type B. In this situation, the result type is B. Further, if the common type is an lvalue, the return type will be an lvalue too.
Delayed variables tend to be commonplace in control structure lambda expressions. For instance, here we use the var function to turn the arguments of for_loop into lambda expressions. The effect of the code is to add 1 to each element of a two-dimensional array:

int a[5][10]; int i; for_each(a, a+5, for_loop(var(i)=0, var(i)<10, ++var(i), _1[var(i)] += 1));
The BLL supports an alternative syntax for control expressions, suggested by Joel de Guzmann. By overloading the operator[] we can get a closer resemblance with the built-in control structures:

if_(condition)[then_part] if_(condition)[then_part].else_[else_part] while_(condition)[body] do_[body].while_(condition) for_(init, condition, increment)[body]

For example, using this syntax the if_then example above can be written as: for_each(a.begin(), a.end(), if_(_1 % 2 == 0)[ cout << _1 ])

As more experience is gained, we may end up deprecating one or the other of these syntaces.

Switch statement
The lambda expressions for switch control structures are more complex since the number of cases may vary. The general form of a switch lambda expression is:

switch_statement(condition, case_statement<label>(lambda expression), case_statement<label>(lambda expression), ... default_statement(lambda expression) )

The condition argument must be a lambda expression that creates a lambda functor with an integral return type. The different cases are created with the case_statement functions, and the optional default case with the default_statement function. The case labels are given as explicitly specified template arguments to case_statement functions and break statements are implicitly part of each case. For example, case_statement<1>(a), where a is some lambda functor, generates the code:

case 1: evaluate lambda functor a; break;
The switch_statement function is specialized for up to 9 case statements.

As a concrete example, the following code iterates over some container v and ouptuts “zero” for each 0, “one” for each 1, and “other: n” for any other value n. Note that another lambda expression is sequenced after the switch_statement to output a line break after each element:

std::for_each(v.begin(), v.end(), ( switch_statement( _1, case_statement<0>(std::cout << constant("zero")), case_statement<1>(std::cout << constant("one")), default_statement(cout << constant("other: ") << _1) ), cout << constant("\n") ) );
Exceptions
The BLL provides lambda functors that throw and catch exceptions. Lambda functors for throwing exceptions are created with the unary function throw_exception. The argument to this function is the exception to be thrown, or a lambda functor which creates the exception to be thrown. A lambda functor for rethrowing exceptions is created with the nullary rethrow function.
Lambda expressions for handling exceptions are somewhat more complex. The general form of a lambda expression for try catch blocks is as follows:

try_catch( lambda expression, catch_exception<type>(lambda expression), catch_exception<type>(lambda expression), ... catch_all(lambda expression) )

The first lambda expression is the try block. Each catch_exception defines a catch block where the explicitly specified template argument defines the type of the exception to catch.

The lambda expression within the catch_exception defines the actions to take if the exception is caught.

Note that the resulting exception handlers catch the exceptions as references, i.e., catch_exception<T>(...) results in the catch block:

catch(T& e) { ... }

The last catch block can alternatively be a call to catch_exception<type> or to catch_all, which is the lambda expression equivalent to catch(...).

The Example 1, “Throwing and handling exceptions in lambda expressions.” demonstrates the use of the BLL exception handling tools. The first handler catches exceptions of type foo_exception. Note the use of _1 placeholder in the body of the handler.
The second handler shows how to throw exceptions, and demonstrates the use of the exception placeholder_e.

It is a special placeholder, which refers to the caught exception object within the handler body.

Here we are handling an exception of type std::exception, which carries a string explaining the cause of the exception.

This explanation can be queried with the zero-argument member function what.

The expression bind(&std::exception::what, _e) creates the lambda function for making that call.

Note that _e cannot be used outside of an exception handler lambda expression.

The last line of the second handler constructs a new exception object and throws that with throw exception.

Constructing and destructing objects within lambda expressions is explained in the section called “Construction and destruction”
Finally, the third handler (catch_all) demonstrates rethrowing exceptions.
Example 1. Throwing and handling exceptions in lambda expressions.
for_each( a.begin(), a.end(), try_catch( bind(foo, _1), // foo may throw catch_exception<foo_exception>( cout << constant("Caught foo_exception: ") << "foo was called with argument = " << _1 ), catch_exception<std::exception>( cout << constant("Caught std::exception: ") << bind(&std::exception::what, _e), throw_exception(bind(constructor<bar_exception>(), _1))) ), catch_all( (cout << constant("Unknown"), rethrow()) ) ) );
Construction and destruction
Operators new and delete can be overloaded, but their return types are fixed.

Particularly, the return types cannot be lambda functors, which prevents them to be overloaded for lambda expressions.

It is not possible to take the address of a constructor, hence constructors cannot be used as target functions in bind expressions.

The same is true for destructors.

As a way around these constraints, BLL defines wrapper classes for new and delete calls, as well as for constructors and destructors.

Instances of these classes are function objects, that can be used as target functions of bind expressions.

For example:

int* a[10]; for_each(a, a+10, _1 = bind(new_ptr<int>())); for_each(a, a+10, bind(delete_ptr(), _1));

The new_ptr<int>() expression creates a function object that calls new int() when invoked, and wrapping that inside bind makes it a lambda functor.

In the same way, the expression delete_ptr() creates a function object that invokes delete on its argument.

Note that new_ptr<T>() can take arguments as well.

They are passed directly to the constructor invocation and thus allow calls to constructors which take arguments.

As an example of constructor calls in lambda expressions, the following code reads integers from two containers x and y, constructs pairs out of them and inserts them into a third container:

vector<pair<int, int> > v; transform(x.begin(), x.end(), y.begin(), back_inserter(v), bind(constructor<pair<int, int> >(), _1, _2));
Table 1, “Construction and destruction related function objects.”
lists all the function objects related to creating and destroying objects, showing the expression to create and call the function object, and the effect of evaluating that expression.

Table 1. Construction and destruction related function objects.

Function object call
Wrapped expression
constructor<T>()(arg_list)
T(arg_list)
destructor()(a)
a.~A()
, where a is of type A
destructor()(pa)
pa->~A()
, where pa is of type A*
new_ptr<T>()(arg_list)
new T(arg_list)
new_array<T>()(sz)
new T[sz]
delete_ptr()(p)
delete p
delete_array()(p)
delete p[]

Special lambda expressions
Preventing argument substitution
When a lambda functor is called, the default behavior is to substitute the actual arguments for the placeholders within all subexpressions.

This section describes the tools to prevent the substitution and evaluation of a subexpression, and explains when these tools should be used.
The arguments to a bind expression can be arbitrary lambda expressions, e.g., other bind expressions.

For example:

int foo(int); int bar(int); ... int i; bind(foo, bind(bar, _1)(i);

The last line makes the call foo(bar(i));

Note that the first argument in a bind expression, the target function, is no exception, and can thus be a bind expression too.

The innermost lambda functor just has to return something that can be used as a target function: another lambda functor, function pointer, pointer to member function etc.

For example, in the following code the innermost lambda functor makes a selection between two functions, and returns a pointer to one of them:

int add(int a, int b) { return a+b; } int mul(int a, int b) { return a*b; }

int(*)(int, int) add_or_mul(bool x) { return x ? add : mul; }

bool condition; int i; int j; ... bind(bind(&add_or_mul, _1), _2, _3)(condition, i, j);
Unlambda
A nested bind expression may occur inadvertently, if the target function is a variable with a type that depends on a template parameter.

Typically the target function could be a formal parameter of a function template.

In such a case, the programmer may not know whether the target function is a lambda functor or not.
Consider the following function template:

template<class F> int nested(const F& f) { int x; ... bind(f, _1)(x); ... }

Somewhere inside the function the formal parameter f is used as a target function in a bind expression.

In order for this bind call to be valid, f must be a unary function.

Suppose the following two calls to nested are made:

int foo(int); int bar(int, int); nested(&foo); nested(bind(bar, 1, _1));

Both are unary functions, or function objects, with appropriate argument and return types, but the latter will not compile.

In the latter call, the bind expression inside nested will become:

bind(bind(bar, 1, _1), _1)

When this is invoked with x, after substituitions we end up trying to call

bar(1, x)(x)

which is an error.

The call to bar returns int, not a unary function or function object.
In the example above, the intent of the bind expression in the nested function is to treat f as an ordinary function object, instead of a lambda functor.

The BLL provides the function template unlambda to express this: a lambda functor wrapped inside unlambda is not a lambda functor anymore, and does not take part into the argument substitution process.

Note that for all other argument types unlambda is an identity operation, except for making non-const objects const.
Using unlambda, the nested function is written as:

template<class F> int nested(const F& f) { int x; ... bind(unlambda(f), _1)(x); ... }
Protect
The protect function is related to unlambda.

It is also used to prevent the argument substitution taking place, but whereas unlambda turns a lambda functor into an ordinary function object for good, protect does this temporarily, for just one evaluation round.

For example:

int x = 1, y = 10; (_1 + protect(_1 + 2))(x)(y);

The first call substitutes x for the leftmost _1, and results in another lambda functor x + (_1 + 2), which after the call with y becomes x + (y + 2), and thus finally 13.
Primary motivation for including protect into the library, was to allow nested STL algorithm invocations (the section called “Nesting STL algorithm invocations”).
Rvalues as actual arguments to lambda functors
Actual arguments to the lambda functors cannot be non-const rvalues. This is due to a deliberate design decision: either we have this restriction, or there can be no side-effects to the actual arguments.

There are ways around this limitation.

We repeat the example from section the section called “About actual arguments to lambda functors” and list the different solutions:

int i = 1; int j = 2; (_1 + _2)(i, j); // ok (_1 + _2)(1, 2); // error (!)
1.
If the rvalue is of a class type, the return type of the function that creates the rvalue should be defined as const. Due to an unfortunate language restriction this does not work for built-in types, as built-in rvalues cannot be const qualified.
2.
If the lambda function call is accessible, the make_const function can be used to constify the rvalue. E.g.:

(_1 + _2)(make_const(1), make_const(2)); // ok

Commonly the lambda function call site is inside a standard algorithm function template, preventing this solution to be used.

3.
If neither of the above is possible, the lambda expression can be wrapped in a const_parameters function. It creates another type of lambda functor, which takes its arguments as const references. For example:

const_parameters(_1 + _2)(1, 2); // ok

Note that const_parameters makes all arguments const. Hence, in the case were one of the arguments is a non-const rvalue, and another argument needs to be passed as a non-const reference, this approach cannot be used.
4.
If none of the above is possible, there is still one solution, which unfortunately can break const correctness.

The solution is yet another lambda functor wrapper, which we have named break_const to alert the user of the potential dangers of this function.

The break_const function creates a lambda functor that takes its arguments as const, and casts away constness prior to the call to the original wrapped lambda functor.

For example: int i; ... (_1 += _2)(i, 2); // error, 2 is a non-const rvalue const_parameters(_1 += _2)(i, 2); // error, i becomes const break_const(_1 += _2)(i, 2); // ok, but dangerous

Note, that the results of break_const or const_parameters are not lambda functors, so they cannot be used as subexpressions of lambda expressions. For instance:

break_const(_1 + _2) + _3; // fails. const_parameters(_1 + _2) + _3; // fails.

However, this kind of code should never be necessary, since calls to sub lambda functors are made inside the BLL, and are not affected by the non-const rvalue problem.
Casts, sizeof and typeid
Cast expressions
The BLL defines its counterparts for the four cast expressions static_cast, dynamic_cast, const_cast and reinterpret_cast.

The BLL versions of the cast expressions have the prefix ll_.

The type to cast to is given as an explicitly specified template argument, and the sole argument is the expression from which to perform the cast.

If the argument is a lambda functor, the lambda functor is evaluated first.

For example, the following code uses ll_dynamic_cast to count the number of derived instances in the container a:

class base {}; class derived : public base {};

vector<base*> a; ... int count = 0; for_each(a.begin(), a.end(), if_then(ll_dynamic_cast<derived*>(_1), ++var(count)));
Sizeof and typeid
The BLL counterparts for these expressions are named ll_sizeof and ll_typeid.

Both take one argument, which can be a lambda expression. The lambda functor created wraps the sizeof or typeid call, and when the lambda functor is called the wrapped operation is performed.

For example:

vector<base*> a; ... for_each(a.begin(), a.end(), cout << bind(&type_info::name, ll_typeid(*_1)));

Here ll_typeid creates a lambda functor for calling typeid for each element.

The result of a typeid call is an instance of the type_info class, and the bind expression creates a lambda functor for calling the name member function of that class.

Nesting STL algorithm invocations
The BLL defines common STL algorithms as function object classes, instances of which can be used as target functions in bind expressions. For example, the following code iterates over the elements of a two-dimensional array, and computes their sum.

int a[100][200]; int sum = 0;

std::for_each(a, a + 100, bind(ll::for_each(), _1, _1 + 200, protect(sum += _1)));

The BLL versions of the STL algorithms are classes, which define the function call operator (or several overloaded ones) to call the corresponding function templates in the std namespace. All these structs are placed in the subnamespace boost::lambda:ll.
Note that there is no easy way to express an overloaded member function call in a lambda expression.

This limits the usefulness of nested STL algorithms, as for instance the begin function has more than one overloaded definitions in container templates.

In general, something analogous to the pseudo-code below cannot be written:

std::for_each(a.begin(), a.end(), bind(ll::for_each(), _1.begin(), _1.end(), protect(sum += _1)));

Some aid for common special cases can be provided though.

The BLL defines two helper function object classes, call_begin and call_end, which wrap a call to the begin and, respectively, end functions of a container, and return the const_iterator type of the container.

With these helper templates, the above code becomes: std::for_each(a.begin(), a.end(), bind(ll::for_each(), bind(call_begin(), _1), bind(call_end(), _1), protect(sum += _1)));
Extending return type deduction system
Extending return type deduction system

In this section, we explain how to extend the return type deduction system to cover user defined operators.

In many cases this is not necessary, as the BLL defines default return types for operators.

For example, the default return type for all comparison operators is bool, and as long as the user defined comparison operators have a bool return type, there is no need to write new specializations for the return type deduction classes.

Sometimes this cannot be avoided, though.

The overloadable user defined operators are either unary or binary.

For each arity, there are two traits templates that define the return types of the different operators.

Hence, the return type system can be extended by providing more specializations for these templates.

The templates for unary functors are

plain_return_type_1<Action, A>

and

return_type_1<Action, A>
, and

plain_return_type_2<Action, A, B>

and

return_type_2<Action, A, B>

respectively for binary functors.

The first parameter (Action) to all these templates is the action class, which specifies the operator.

Operators with similar return type rules are grouped together into action groups, and only the action class and action group together define the operator unambiguously.

As an example, the action type arithmetic_action<plus_action> stands for operator+.

The complete listing of different action types is shown in Table 2, “Action types”.
The latter parameters, A in the unary case, or A and B in the binary case, stand for the argument types of the operator call.

The two sets of templates, plain_return_type_n and return_type_n (n is 1 or 2) differ in the way how parameter types are presented to them.

For the former templates, the parameter types are always provided as non-reference types, and do not have const or volatile qualifiers.

This makes specializing easy, as commonly one specialization for each user defined operator, or operator group, is enough.

On the other hand, if a particular operator is overloaded for different cv-qualifications of the same argument types, and the return types of these overloaded versions differ, a more fine-grained control is needed.

Hence, for the latter templates, the parameter types preserve the cv-qualifiers, and are non-reference types as well.

The downside is, that for an overloaded set of operators of the kind described above, one may end up needing up to 16 return_type_2 specializations.
Suppose the user has overloaded the following operators for some user defined types X, Y and Z:

Z operator+(const X&, const Y&); Z operator-(const X&, const Y&);

Now, one can add a specialization stating, that if the left hand argument is of type X, and the right hand one of type Y, the return type of all such binary arithmetic operators is Z:

namespace boost { namespace lambda {

template<class Act> struct plain_return_type_2<arithmetic_action<Act>, X, Y> { typedef Z type; };

} }

Having this specialization defined, BLL is capable of correctly deducing the return type of the above two operators.

Note, that the specializations must be in the same namespace, ::boost::lambda, with the primary template.

For brevity, we do not show the namespace definitions in the examples below.
It is possible to specialize on the level of an individual operator as well, in addition to providing a specialization for a group of operators. Say, we add a new arithmetic operator for argument types X and Y:

X operator*(const X&, const Y&);

Our first rule for all arithmetic operators specifies that the return type of this operator is Z, which obviously is not the case. Hence, we provide a new rule for the multiplication operator:

template<> struct plain_return_type_2<arithmetic_action<multiply_action>, X, Y> { typedef X type; };
The specializations can define arbitrary mappings from the argument types to the return type.

Suppose we have some mathematical vector type, templated on the element type:

template <class T> class my_vector;

Suppose the addition operator is defined between any two my_vector instantiations, as long as the addition operator is defined between their element types.

Furthermore, the element type of the resulting my_vector is the same as the result type of the addition between the element types.

E.g., adding my_vector<int> and my_vector<double> results in my_vector<double>.

The BLL has traits classes to perform the implicit built-in and standard type conversions between integral, floating point, and complex classes.

Using BLL tools, the addition operator described above can be defined as:

template<class A, class B> my_vector<typename return_type_2<arithmetic_action<plus_action>, A, B>::type> operator+(const my_vector<A>& a, const my_vector<B>& b) { typedef typename return_type_2<arithmetic_action<plus_action>, A, B>::type res_type; return my_vector<res_type>(); }
To allow BLL to deduce the type of my_vector additions correctly, we can define:

template<class A, class B> class plain_return_type_2<arithmetic_action<plus_action>, my_vector<A>, my_vector<B> > { typedef typename return_type_2<arithmetic_action<plus_action>, A, B>::type res_type; public: typedef my_vector<res_type> type; };
Note, that we are reusing the existing specializations for the BLL return_type_2 template, which require that the argument types are references.
Table 2. Action types

+
arithmetic_action<plus_action>
-
arithmetic_action<minus_action>
*
arithmetic_action<multiply_action>
/
arithmetic_action<divide_action>
%
arithmetic_action<remainder_action>
+
unary_arithmetic_action<plus_action>
-
unary_arithmetic_action<minus_action>
&
bitwise_action<and_action>
|
bitwise_action<or_action>
~
bitwise_action<not_action>
^
bitwise_action<xor_action>
<<
bitwise_action<leftshift_action_no_stream>
>>
bitwise_action<rightshift_action_no_stream>
&&
logical_action<and_action>
||
logical_action<or_action>
!
logical_action<not_action>
<
relational_action<less_action>
>
relational_action<greater_action>
<=
relational_action<lessorequal_action>
>=
relational_action<greaterorequal_action>
==
relational_action<equal_action>
!=
relational_action<notequal_action>
+=
arithmetic_assignment_action<plus_action>
-=
arithmetic_assignment_action<minus_action>
*=
arithmetic_assignment_action<multiply_action>
/=
arithmetic_assignment_action<divide_action>
%=
arithmetic_assignment_action<remainder_action>
&=
bitwise_assignment_action<and_action>
=|
bitwise_assignment_action<or_action>
^=
bitwise_assignment_action<xor_action>
<<=
bitwise_assignment_action<leftshift_action>
>>=
bitwise_assignment_action<rightshift_action>
++
pre_increment_decrement_action<increment_action>
--
pre_increment_decrement_action<decrement_action>
++
post_increment_decrement_action<increment_action>
--
post_increment_decrement_action<decrement_action>
&
other_action<address_of_action>
*
other_action<contents_of_action>
,
other_action<comma_action>

Practical considerations
Practical considerations
Performance
In theory, all overhead of using STL algorithms and lambda functors compared to hand written loops can be optimized away, just as the overhead from standard STL function objects and binders can.

Depending on the compiler, this can also be true in practice. We ran two tests with the GCC 3.0.4 compiler on 1.5 GHz Intel Pentium 4. The optimization flag -03 was used.
In the first test we compared lambda functors against explicitly written function objects. We used both of these styles to define unary functions which multiply the argument repeatedly by itself. We started with the identity function, going up to x5. The expressions were called inside a std::transform loop, reading the argument from one std::vector<int> and placing the result into another. The length of the vectors was 100 elements. The running times are listed in Table 3, “Test 1CPU time of expressions with integer multiplication written as a lambda expression and as a traditional hand-coded function object class. The running times are expressed in arbitrary units.”.

We can observe that there is no significant difference between the two approaches.
In the second test we again used std::transform to perform an operation to each element in a 100-element long vector. This time the element type of the vectors was double and we started with very simple arithmetic expressions and moved to more complex ones. The running times are listed in Table 4, “Test 2CPU time of arithmetic expressions written as lambda expressions, as classic STL unnamed functions (using compose2, bind1st etc.) and as traditional hand-coded function object classes. Using BLL terminology, a and b are bound arguments in the expressions, and x is open. All variables were of types double. The running times are expressed in arbitrary units.”.

Here, we also included classic STL style unnamed functions into tests. We do not show these expressions, as they get rather complex. For example, the last expression in Table 4, “Test 2CPU time of arithmetic expressions written as lambda expressions, as classic STL unnamed functions (using compose2, bind1st etc.) and as traditional hand-coded function object classes. Using BLL terminology, a and b are bound arguments in the expressions, and x is open. All variables were of types double. The running times are expressed in arbitrary units.” written with classic STL tools contains 7 calls to compose2, 8 calls to bind1st and altogether 14 constructor invocations for creating multiplies, minus and plus objects.

In this test the BLL expressions are a little slower (roughly 10% on average, less than 14% in all cases) than the corresponding hand-written function objects. The performance hit is a bit greater with classic STL expressions, up to 27% for the simplest expressios.
The tests suggest that the BLL does not introduce a loss of performance compared to STL function objects. With a reasonable optimizing compiler, one should expect the performance characteristics be comparable to using classic STL. Moreover, with simple expressions the performance can be expected to be close to that of explicitly written function objects.

Note however, that evaluating a lambda functor consist of a sequence of calls to small functions that are declared inline. If the compiler fails to actually expand these functions inline, the performance can suffer. The running time can more than double if this happens. Although the above tests do not include such an expression, we have experienced this for some seemingly simple expressions.

Table 3. Test 1CPU time of expressions with integer multiplication written as a lambda expression and as a traditional hand-coded function object class. The running times are expressed in arbitrary units.

expression
lambda expression
hand-coded function object
x
240
230
x*x
340
350
x*x*x
770
760
x*x*x*x
1180
1210
x*x*x*x*x
1950
1910

Table 4. Test 2CPU time of arithmetic expressions written as lambda expressions, as classic STL unnamed functions (using compose2, bind1st etc.) and as traditional hand-coded function object classes. Using BLL terminology, a and b are bound arguments in the expressions, and x is open. All variables were of types double. The running times are expressed in arbitrary units.

expression
lambda expression
classic STL expression
hand-coded function object
ax
330
370
290
-ax
350
370
310
ax-(a+x)
470
500
420
(ax-(a+x))(a+x)
620
670
600
((ax) - (a+x))(bx - (b+x))(ax - (b+x))(bx - (a+x))
1660
1660
1460

Some additional performance testing with an earlier version of the library is described [Jär00].
About compiling
The BLL uses templates rather heavily, performing numerous recursive instantiations of the same templates. This has (at least) three implications: • While it is possible to write incredibly complex lambda expressions, it probably isn't a good idea. Compiling such expressions may end up requiring a lot of memory at compile time, and being slow to compile. • The types of lambda functors that result from even the simplest lambda expressions are cryptic. Usually the programmer doesn't need to deal with the lambda functor types at all, but in the case of an error in a lambda expression, the compiler usually outputs the types of the lambda functors involved. This can make the error messages very long and difficult to interpret, particularly if the compiler outputs the whole chain of template instantiations. • The C++ Standard suggests a template nesting level of 17 to help detect infinite recursion. Complex lambda templates can easily exceed this limit. Most compilers allow a greater number of nested templates, but commonly require the limit explicitly increased with a command line argument.
Portability
The BLL works with the following compilers, that is, the compilers are capable of compiling the test cases that are included with the BLL:

•
GCC 3.0.4
•
KCC 4.0f with EDG 2.43.1
•
GCC 2.96 (fails with one test case, the exception_test.cpp results in an internal compiler error. )

Test coverage
The following list describes the test files included and the features that each file covers:

•
bind_tests_simple.cpp
: Bind expressions of different arities and types of target functions: function pointers, function objects and member functions. Function composition with bind expressions.
•
bind_tests_simple_function_references.cpp
: Repeats all tests from bind_tests_simple.cpp where the target function is a function pointer, but uses function references instead.
•
bind_tests_advanced.cpp
: Contains tests for nested bind expressions, unlambda, protect, const_parameters and break_const. Tests passing lambda functors as actual arguments to other lambda functors, currying, and using the sig template to specify the return type of a function object.
•
operator_tests_simple.cpp
: Tests using all operators that are overloaded for lambda expressions, that is, unary and binary arithmetic, bitwise, comparison, logical, increment and decrement, compound, assignment, subscrict, address of, dereference, and comma operators. The streaming nature of shift operators is tested, as well as pointer arithmetic with plus and minus operators.
•
member_pointer_test.cpp
: The pointer to member operator is complex enough to warrant a separate test file.
•
control_structures.cpp
: Tests for the looping and if constructs.
•
switch_construct.cpp
: Includes tests for all supported arities of the switch statement, both with and without the default case.
•
exception_test.cpp
: Includes tests for throwing exceptions and for try/catch constructs with varying number of catch blocks.
•
constructor_tests.cpp
: Contains tests for constructor, destructor, new_ptr, delete_ptr, new_array and delete_array.
•
cast_test.cpp
: Tests for the four cast expressions, as well as typeid and sizeof.
•
extending_return_type_traits.cpp
: Tests extending the return type deduction system for user defined types. Contains several user defined operators and the corresponding specializations for the return type deduction templates.
•
is_instance_of_test.cpp
: Includes tests for an internally used traits template, which can detect whether a given type is an instance of a certain template or not.
•
bll_and_function.cpp
: Contains tests for using boost::function together with lambda functors.
Relation to other Boost libraries
Relation to other Boost libraries
Boost Function
Sometimes it is convenient to store lambda functors in variables. However, the types of even the simplest lambda functors are long and unwieldy, and it is in general unfeasible to declare variables with lambda functor types. The Boost Function library[function] defines wrappers for arbitrary function objects, for example lambda functors; and these wrappers have types that are easy to type out.

For example:

boost::function<int(int, int)> f = _1 + _2; boost::function<int&(int&)> g = (_1 += 10); int i = 1, j = 2; f(i, j); // returns 3 g(i); // sets i to = 11;

The return and parameter types of the wrapped function object must be written explicilty as the template argument to the wrapper template boost::function; even when lambda functors, which otherwise have generic parameters, are wrapped. Wrapping a function object with boost::function introduces a performance cost comparable to virtual function dispatch, though virtual functions are not actually used.

Note that storing lambda functors inside boost::function introduces a danger. Certain types of lambda functors may store references to the bound arguments, instead as taking copies of the arguments of the lambda expression. When temporary lambda functor objects are used in STL algorithm invocations this is always safe, as the lambda functor gets destructed immediately after the STL algortihm invocation is completed.

However, a lambda functor wrapped inside boost::function may continue to exist longer, creating the possibility of dangling references. For example:

int* sum = new int(); *sum = 0; boost::function<int&(int)> counter = *sum += _1; counter(5); // ok, *sum = 5; delete sum; counter(3); // error, *sum does not exist anymore
Boost Bind
The Boost Bind
[bind]
library has partially overlapping functionality with the BLL. Basically, the Boost Bind library (BB in the sequel) implements the bind expression part of BLL. There are, however, some semantical differerences.
The BLL and BB evolved separately, and have different implementations. This means that the bind expressions from the BB cannot be used within bind expressions, or within other type of lambda expressions, of the BLL. The same holds for using BLL bind expressions in the BB. The libraries can coexist, however, as the names of the BB library are in boost namespace, whereas the BLL names are in boost::lambda namespace.
The BLL requires a compiler that is reasonably conformant to the C++ standard, whereas the BB library is more portable, and works with a larger set of compilers.
The following two sections describe what are the semantic differences between the bind expressions in BB and BLL.
First argument of bind expression

In BB the first argument of the bind expression, the target function, is treated differently from the other arguments, as no argument substitution takes place within that argument. In BLL the first argument is not a special case in this respect.

For example:

template<class F> int foo(const F& f) { int x; .. bind(f, _1)(x); ... }
int bar(int, int); nested(bind(bar, 1, _1));

The bind expression inside foo becomes: bind(bind(bar, 1, _1), _1)(x)

The BLL interpretes this as: bar(1, x)(x) whereas the BB library as bar(1, x)

To get this functionality in BLL, the bind expression inside the foo function can be written as: bind(unlambda(f), _1)(x); as explained in the section called “Unlambda”.

The BB library supports up to nine placeholders, while the BLL defines only three placeholders. The rationale for not providing more, is that the highest arity of the function objects accepted by any STL algorithm is two. The placeholder count is easy to increase in the BB library. In BLL it is possible, but more laborous. The BLL currently passes the actual arguments to the lambda functors internally just as they are and does not wrap them inside a tuple object. The reason for this is that some widely used compilers are not capable of optimizing the intermediate tuple objects away. The creation of the intermediate tuples would cause a significant performance hit, particularly for the simplest (and thus the most common) lambda functors. We are working on a hybrid approach, which will allow more placeholders but not compromise the performance of simple lambda functors.
Contributors
Contributors

The main body of the library was written by Jaakko Järvi and Gary Powell. We've got outside help, suggestions and ideas from Jeremy Siek, Peter Higley, Peter Dimov, Valentin Bonnard, William Kempf. We would particularly like to mention Joel de Guzmann and his work with Phoenix which has influenced BLL significantly, making it considerably simpler to extend the library with new features.

Rationale for some of the design decisions

Rationale for some of the design decisions

Appendix A. Rationale for some of the design decisions
Lambda functor arity
The highest placeholder index in a lambda expression determines the arity of the resulting function object. However, this is just the minimal arity, as the function object can take arbitrarily many arguments; those not needed are discarded. Consider the two bind expressions and their invocations below:

bind(g, _3, _3, _3)(x, y, z); bind(g, _1, _1, _1)(x, y, z);

This first line discards arguments x and y, and makes the call: g(z, z, z) whereas the second line discards arguments y and z, and calls: g(x, x, x) In earlier versions of the library, the latter line resulted in a compile time error.

This is basically a tradeoff between safety and flexibility, and the issue was extensively discussed during the Boost review period of the library. The main points for the strict arity checking was that it might catch a programming error at an earlier time and that a lambda expression that explicitly discards its arguments is easy to write: (_3, bind(g, _1, _1, _1))(x, y, z); This lambda expression takes three arguments. The left-hand argument of the comma operator does nothing, and as comma returns the result of evaluating the right-hand argument we end up with the call g(x, x, x) even with the strict arity.
The main points against the strict arity checking were that the need to discard arguments is commonplace, and should therefore be straightforward, and that strict arity checking does not really buy that much more safety, particularly as it is not symmetric. For example, if the programmer wanted to write the expression _1 + _2 but mistakenly wrote _1 + 2, with strict arity checking, the complier would spot the error. However, if the erroneous expression was 1 + _2 instead, the error would go unnoticed. Furthermore, weak arity checking simplifies the implementation a bit. Following the recommendation of the Boost review, strict arity checking was dropped.
Bibliography
[STL94] A. A. Stepanov and M. Lee. The Standard Template Library. Hewlett-Packard Laboratories. 1994. www.hpl.hp.com/techreports.
[SGI02] The SGI Standard Template Library. 2002. www.sgi.com/tech/stl/.
[C++98] International Standard, Programming Languages – C++. ISO/IEC:14882. 1998.
[Jär99] Jaakko Järvi. C++ Function Object Binders Made Easy. . Lecture Notes in Computer Science. 1977. Springer. 2000.
[Jär00] Jaakko Järvi. Gary Powell. The Lambda Library : Lambda Abstraction in C++. Turku Centre for Computer Science. Technical Report . 378. 2000. www.tucs.fi/publications.
[Jär01] Jaakko Järvi. Gary Powell. The Lambda Library : Lambda Abstraction in C++. Second Workshop on C++ Template Programming. Tampa Bay, OOPSLA'01. . 2001. www.oonumerics.org/tmpw01/.
[Jär03] Jaakko Järvi. Gary Powell. Andrew Lumsdaine. The Lambda Library : unnamed functions in C++. . Software - Practice and Expreience. 33:259-291. 2003.
[tuple] The Boost Tuple Library. www.boost.org/libs/tuple/doc/tuple_users_guide.html. 2002.
[type_traits] The Boost type_traits. www.boost.org/libs/type_traits/. 2002.
[ref] Boost ref. www.boost.org/libs/bind/ref.html. 2002.
[bind] Boost Bind Library. www.boost.org/libs/bind/bind.html. 2002.
[function] Boost Function Library. www.boost.org/libs/function/. 2002.
[fc++] The FC++ library: Functional Programming in C++. Yannis Smaragdakis. Brian McNamara. www.cc.gatech.edu/~yannis/fc++/. 2002.

Boost.Program_options

Boost.Program_options

Boost.Program_options
Vladimir Prus
Copyright © 2002-2004 Vladimir Prus
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
Why would you use such a library, and why is it better than parsing your command line by straightforward hand-written code? •It's easier. The syntax for declaring options is simple, and the library itself is small. Things like conversion of option values to desired type and storing into program variables are handled automatically. •Error reporting is better. All the problems with the command line are reported, while hand-written code can just misparse the input. In addition, the usage message can be automatically generated, to avoid falling out of sync with the real list of options.•Options can be read from anywhere. Sooner or later the command line will be not enough for your users, and you'll want config files or maybe even environment variables. These can be added without significant effort on your part.
Now let's see some examples of the library usage in the the section called “Tutorial”.
Tutorial
Tutorial
In this section, we'll take a look at the most common usage scenarios of the program_options library, starting with the simplest one. The examples show only the interesting code parts, but the complete programs can be found in the "BOOST_ROOT/libs/program_options/example" directory. Through all the examples, we'll assume that the following namespace alias is in effect: namespace po = boost::program_options;
Getting Started
The first example is the simplest possible: it only handles two options. Here's the source code (the full program is in "example/first.cpp"):

// Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("compression", po::value<int>(), "set compression level") ;

po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm);

if (vm.count("help")) { cout << desc << "\n"; return 1; }

if (vm.count("compression")) { cout << "Compression level was set to " << vm["compression"].as<int>() << ".\n"; } else { cout << "Compression level was not set.\n"; }
We start by declaring all allowed options using the options_description class. The add_options method of that class returns a special proxy object that defines operator(). Calls to that operator actually declare options. The parameters are option name, information about value, and option description. In this example, the first option has no value, and the second one has a value of type int.
After that, an object of class variables_map is declared. That class is intended to store values of options, and can store values of arbitrary types. Next, the calls to store, parse_command_line and notify functions cause vm to contain all the options found on the command line.
And now, finally, we can use the options as we like. The variables_map class can be used just like std::map, except that values stored there must be retrieved with the as method shown above. (If the type specified in the call to the as method is different from the actually stored type, an exception is thrown.)
It's now a good time to try compiling the code yourself, but if you're not yet ready, here's an example session: $bin/gcc/debug/first Compression level was not set. $bin/gcc/debug/first --help Allowed options: --help : produce help message --compression arg : set compression level $bin/gcc/debug/first --compression 10 Compression level was set to 10.
Option Details
An option value, surely, can have other types than int, and can have other interesting properties, which we'll discuss right now. The complete version of the code snipped below can be found in "example/options_description.cpp".
Imagine we're writing a compiler. It should take the optimization level, a number of include paths, and a number of input files, and perform some interesting work. Let's describe the options: int opt; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", po::value< vector<string> >(), "include path") ("input-file", po::value< vector<string> >(), "input file") ;
The "--help" option should be familiar from the previous example. It's a good idea to have this option in all cases.
The "optimization" option shows two new features. First, we specify the address of the variable(&opt). After storing values, that variable will have the value of the option. Second, we specify a default value of 10, which will be used if no value is specified by the user.
The "include-path" option is an example of the only case where the interface of the options_description class serves only one source -- the command line. Users typically like to use short option names for common options, and the "include-path,I" name specifies that short option name is "I". So, both "--include-path" and "-I" can be used.
The "input-file" option specifies the list of files to process. That's okay for a start, but, of course, writing something like: compiler --input-file=a.cpp is a little non-standard, compared with compiler a.cpp We'll address this in a moment.
The command line tokens which have no option name, as above, are called "positional options" by this library. They can be handled too. With a little help from the user, the library can decide that "a.cpp" really means the same as "--input-file=a.cpp". Here's the additional code we need: po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(ac, av). options(desc).positional(p).run(), vm); po::notify(vm);
The first two lines say that all positional options should be translated into "input-file" options. Also note that we use the command_line_parser class to parse the command line, not the parse_command_line function. The latter is a convenient wrapper for simple cases, but now we need to pass additional information.
By now, all options are described and parsed. We'll save ourselves the trouble of implementing the rest of the compiler logic and only print the options: if (vm.count("include-path")) { cout << "Include paths are: " << vm["include-path"].as< vector<string> >() << "\n"; } if (vm.count("input-file")) { cout << "Input files are: " << vm["input-file"].as< vector<string> >() << "\n"; } cout << "Optimization level is " << opt << "\n";
Here's an example session: $bin/gcc/debug/options_description --help Usage: options_description [options] Allowed options: --help : produce help message --optimization arg : optimization level -I [ --include-path ] arg : include path --input-file arg : input file $bin/gcc/debug/options_description Optimization level is 10 $bin/gcc/debug/options_description --optimization 4 -I foo a.cpp Include paths are: foo Input files are: a.cpp Optimization level is 4
Oops, there's a slight problem. It's still possible to specify the "--input-file" option, and usage message says so, which can be confusing for the user. It would be nice to hide this information, but let's wait for the next example.
Multiple Sources
It's quite likely that specifying all options to our compiler on the command line will annoy users. What if a user installs a new library and wants to always pass an additional command line element? What if he has made some choices which should be applied on every run? It's desirable to create a config file with common settings which will be used together with the command line.
Of course, there will be a need to combine the values from command line and config file. For example, the optimization level specified on the command line should override the value from the config file. On the other hand, include paths should be combined.
Let's see the code now. The complete program is in "examples/multiple_sources.cpp". The option definition has two interesting details. First, we declare several instances of the options_description class. The reason is that, in general, not all options are alike. Some options, like "input-file" above, should not be presented in an automatic help message. Some options make sense only in the config file. Finally, it's nice to have some structure in the help message, not just a long list of options. Let's declare several option groups: // Declare a group of options that will be // allowed only on command line po::options_description generic("Generic options"); generic.add_options() ("version,v", "print version string") ("help", "produce help message") ; // Declare a group of options that will be // allowed both on command line and in // config file po::options_description config("Configuration"); config.add_options() ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", po::value< vector<string> >()->composing(), "include path") ; // Hidden options, will be allowed both on command line and // in config file, but will not be shown to the user. po::options_description hidden("Hidden options"); hidden.add_options() ("input-file", po::value< vector<string> >(), "input file") ; Note the call to the composing method in the declaration of the "include-path" option. It tells the library that values from different sources should be composed together, as we'll see shortly.
The add method of the options_description class can be used to further group the options: po::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); po::options_description config_file_options; config_file_options.add(config).add(hidden); po::options_description visible("Allowed options"); visible.add(generic).add(config);
The parsing and storing of values follows the usual pattern, except that we additionally call parse_config_file, and call the store function twice. But what happens if the same value is specified both on the command line and in config file? Usually, the value stored first is preferred. This is what happens for the "--optimization" option. For "composing" options, like "include-file", the values are merged.
Here's an example session: $bin/gcc/debug/multiple_sources Include paths are: /opt Optimization level is 1 $bin/gcc/debug/multiple_sources --help Allows options: Generic options: -v [ --version ] : print version string --help : produce help message Configuration: --optimization n : optimization level -I [ --include-path ] path : include path $bin/gcc/debug/multiple_sources --optimization=4 -I foo a.cpp b.cpp Include paths are: foo /opt Input files are: a.cpp b.cpp Optimization level is 4 The first invocation uses values from the configuration file. The second invocation also uses values from command line. As we see, the include paths on the command line and in the configuration file are merged, while optimization is taken from the command line.
Library Overview
Library Overview
In the tutorial section, we saw several examples of library usage. Here we will describe the overall library design including the primary components and their function.
The library has three main components: •The options description component, which describes the allowed options and what to do with the values of the options. •The parsers component, which uses this information to find option names and values in the input sources and return them. •The storage component, which provides the interface to access the value of an option. It also converts the string representation of values that parsers return into desired C++ types.
To be a little more concrete, the options_description class is from the options description component, the parse_command_line function is from the parsers component, and the variables_map class is from the storage component.
In the tutorial we've learned how those components can be used by the main function to parse the command line and config file. Before going into the details of each component, a few notes about the world outside of main.
For that outside world, the storage component is the most important. It provides a class which stores all option values and that class can be freely passed around your program to modules which need access to the options. All the other components can be used only in the place where the actual parsing is the done. However, it might also make sense for the individual program modules to describe their options and pass them to the main module, which will merge all options. Of course, this is only important when the number of options is large and declaring them in one place becomes troublesome.
Options Description Component
The options description component has three main classes: option_description, value_semantic and options_description. The first two together describe a single option. The option_description class contains the option's name, description and a pointer to value_semantic, which, in turn, knows the type of the option's value and can parse the value, apply the default value, and so on. The options_description class is a container for instances of option_description.
For almost every library, those classes could be created in a conventional way: that is, you'd create new options using constructors and then call the add method of options_description. However, that's overly verbose for declaring 20 or 30 options. This concern led to creation of the syntax that you've already seen: options_description desc; desc.add_options() ("help", "produce help") ("optimization", value<int>()->default_value(10), "optimization level") ;
The call to the value function creates an instance of a class derived from the value_semantic class: typed_value. That class contains the code to parse values of a specific type, and contains a number of methods which can be called by the user to specify additional information. (This essentially emulates named parameters of the constructor.) Calls to operator() on the object returned by add_options forward arguments to the constructor of the option_description class and add the new instance.
Note that in addition to the value, library provides the bool_switch function, and user can write his own function which will return other subclasses of value_semantic with different behaviour. For the remainder of this section, we'll talk only about the value function.
The information about an option is divided into syntactic and semantic. Syntactic information includes the name of the option and the number of tokens which can be used to specify the value. This information is used by parsers to group tokens into (name, value) pairs, where value is just a vector of strings (std::vector<std::string>). The semantic layer is responsible for converting the value of the option into more usable C++ types.
This separation is an important part of library design. The parsers use only the syntactic layer, which takes away some of the freedom to use overly complex structures. For example, it's not easy to parse syntax like: calc --expression=1 + 2/3 because it's not possible to parse 1 + 2/3 without knowing that it's a C expression. With a little help from the user the task becomes trivial, and the syntax clear: calc --expression="1 + 2/3"
Syntactic information
The syntactic information is provided by the boost::program_options::options_description class and some methods of the boost::program_options::value_semantic class. The simplest usage is illustrated below: options_description desc; desc.add_options() ("help", "produce help message") ; This declares one option named "help" and associates a description with it. The user is not allowed to specify any value.
To make an option accept a value, you'd need the value function mentioned above: options_description desc; desc.add_options() ("compression", "compression level", value<string>()) ("verbose", "verbosity level", value<string>()->implicit()) ("email", "email to send to", value<string>()->multitoken()); With these declarations, the user must specify a value for the first option, using a single token. For the second option, the user may either provide a single token for the value, or no token at all. For the last option, the value can span several tokens. For example, the following command line is OK: test --compression 10 --verbose --email beadle@mars beadle2@mars
Semantic information
The semantic information is completely provided by the boost::program_options::value_semantic class. For example: options_description desc; desc.add_options() ("compression", "compression level", value<int>()->default(10)); ("email", "email", value< vector<string> >() ->composing()->notify(&your_function); These declarations specify that default value of the first option is 10, that the second option can appear several times and all instances should be merged, and that after parsing is done, the library will call function &your_function, passing the value of the "email" option as argument.
Positional options
Our definition of option as (name, value) pairs is simple and useful, but in one special case of the command line, there's a problem. A command line can include a positional option, which does not specify any name at all, for example: archiver --compression=9 /etc/passwd Here, the "/etc/passwd" element does not have any option name.
One solution is to ask the user to extract positional options himself and process them as he likes. However, there's a nicer approach -- provide a method to automatically assign the names for positional options, so that the above command line can be interpreted the same way as: archiver --compression=9 --input-file=/etc/passwd
The positional_options_description class allows the command line parser to assign the names. The class specifies how many positional options are allowed, and for each allowed option, specifies the name. For example: positional_options_description pd; pd.add("input-file", 1, 1); specifies that for exactly one, first, positional option the name will be "input-file".
It's possible to specify that a number, or even all positional options, be given the same name. positional_options_description pd; pd.add("output-file", 2, 2).add_optional("input-file", 0, -1); In the above example, the first two positional options will be associated with name "output-file", and any others with the name "input-file".
Parsers Component
The parsers component splits input sources into (name, value) pairs. Each parser looks for possible options and consults the options description component to determine if the option is known and how its value is specified. In the simplest case, the name is explicitly specified, which allows the library to decide if such option is known. If it is known, the value_semantic instance determines how the value is specified. (If it is not known, an exception is thrown.) Common cases are when the value is explicitly specified by the user, and when the value cannot be specified by the user, but the presence of the option implies some value (for example, true). So, the parser checks that the value is specified when needed and not specified when not needed, and returns new (name, value) pair.
To invoke a parser you typically call a function, passing the options description and command line or config file or something else. The results of parsing are returned as an instance of the parsed_options class. Typically, that object is passed directly to the storage component. However, it also can be used directly, or undergo some additional processing.
There are three exceptions to the above model -- all related to traditional usage of the command line. While they require some support from the options description component, the additional complexity is tolerable. •The name specified on the command line may be different from the option name -- it's common to provide a "short option name" alias to a longer name. It's also common to allow an abbreviated name to be specified on the command line. •Sometimes it's desirable to specify value as several tokens. For example, an option "--email-recipient" may be followed by several emails, each as a separate command line token. This behaviour is supported, though it can lead to parsing ambiguities and is not enabled by default. •The command line may contain positional options -- elements which don't have any name. The command line parser provides a mechanism to guess names for such options, as we've seen in the tutorial.
Storage Component
The storage component is responsible for: •Storing the final values of an option into a special class and in regular variables•Handling priorities among different sources.•Calling user-specified notify functions with the final values of options.
Let's consider an example: variables_map vm; store(parse_command_line(argc, argv, desc), vm); store(parse_config_file("example.cfg", desc), vm); notify(vm); The variables_map class is used to store the option values. The two calls to the store function add values found on the command line and in the config file. Finally the call to the notify function runs the user-specified notify functions and stores the values into regular variables, if needed.
The priority is handled in a simple way: the store function will not change the value of an option if it's already assigned. In this case, if the command line specifies the value for an option, any value in the config file is ignored.
Warning
Don't forget to call the notify function after you've stored all parsed values.
Annotated List of Symbols
The following table describes all the important symbols in the library, for quick access.

Symbol
Description
Options description component
options_description
describes a number of options
value
defines the option's value
Parsers component
parse_command_line
parses command line
parse_config_file
parses config file
parse_environment
parses environment
Storage component
variables_map
storage for option values

How To
How To
This section describes how the library can be used in specific situations.
Non-conventional Syntax
Sometimes, standard command line syntaxes are not enough. For example, the gcc compiler has "-frtti" and -fno-rtti" options, and this syntax is not directly supported.
For such cases, the library allows the user to provide an additional parser -- a function which will be called on each command line element, before any processing by the library. If the additional parser recognises the syntax, it returns the option name and value, which are used directly. The above example can be handled by the following code:
pair<string, string> reg_foo(const string& s) { if (s.find("-f") == 0) { if (s.substr(2, 3) == "no-") return make_pair(s.substr(5), string("false")); else return make_pair(s.substr(2), string("true")); } else { return make_pair(string(), string()); } }
Here's the definition of the additional parser. When parsing the command line, we pass the additional parser: store(command_line_parser(ac, av).options(desc).extra_parser(reg_foo) .run(), vm); The complete example can be found in the "example/custom_syntax.cpp" file.
Response Files
Some operating system have very low limits of the command line length. The common way to work around those limitations is using response files. A response file is just a configuration file which uses the same syntax as the command line. If the command line specifies a name of response file to use, it's loaded and parsed in addition to the command line. The library does not provide direct support for response files, so you'll need to write some extra code.
First, you need to define an option for the response file: ("response-file", value<string>(), "can be specified with '@name', too")
Second, you'll need an additional parser to support the standard syntax for specifying response files: "@file": pair<string, string> at_option_parser(string const&s) { if ('@' == s[0]) return std::make_pair(string("response-file"), s.substr(1)); else return pair<string, string>(); }
Finally, when the "response-file" option is found, you'll have to load that file and pass it to the command line parser. This part is the hardest. We'll use the Boost.Tokenizer library, which works but has some limitations. You might also consider Boost.StringAlgo. The code is: if (vm.count("response-file")) { // Load the file and tokenize it ifstream ifs(vm["response-file"].as<string>().c_str()); if (!ifs) { cout << "Could no open the response file\n"; return 1; } // Read the whole file into a string stringstream ss; ss << ifs.rdbuf(); // Split the file content char_separator<char> sep(" \n\r"); tokenizer<char_separator<char> > tok(ss.str(), sep); vector<string> args; copy(tok.begin(), tok.end(), back_inserter(args)); // Parse the file and store the options store(command_line_parser(args).options(desc).run(), vm); } The complete example can be found in the "example/response_file.cpp" file.
Winmain Command Line
On the Windows operating system, GUI applications receive the command line as a single string, not split into elements. For that reason, the command line parser cannot be used directly. At least on some compilers, it is possible to obtain the split command line, but it's not clear if all compilers support the same mechanism on all versions of the operating system. The split_command_line function is a portable mechanism provided by the library.
Here's an example of use: vector<string> args = split_winmain(lpCmdLine); store(command_line_parser(args).options(desc).run(), vm); The function is an overload for wchar_t strings, so can also be used in Unicode applications.
Option Groups and Hidden Options
Having a single instance of the options_description class with all the program's options can be problematic: •Some options make sense only for specific source, for example, configuration files.•The user would prefer some structure in the generated help message.•Some options shouldn't appear in the generated help message at all.
To solve the above issues, the library allows a programmer to create several instances of the options_description class, which can be merged in different combinations. The following example will define three groups of options: command line specific, and two options group for specific program modules, only one of which is shown in the generated help message.
Each group is defined using standard syntax. However, you should use reasonable names for each options_description instance: options_description general("General options"); general.add_options() ("help", "produce a help message") ("help-module", value<string>()->implicit(), "produce a help for a given module") ("version", "output the version number") ; options_description gui("GUI options"); gui.add_options() ("display", value<string>(), "display to use") ; options_description backend("Backend options"); backend.add_options() ("num-threads", value<int>(), "the initial number of threads") ;
After declaring options groups, we merge them in two combinations. The first will include all options and be used for parsing. The second will be used for the "--help" option. // Declare an options description instance which will include // all the options options_description all("Allowed options"); all.add(general).add(gui).add(backend); // Declare an options description instance which will be shown // to the user options_description visible("Allowed options"); visible.add(general).add(gui);
What is left is to parse and handle the options: variables_map vm; store(parse_command_line(ac, av, all), vm); if (vm.count("help")) { cout << visible; return 0; } if (vm.count("help-module")) { const string& s = vm["help-module"].as<string>(); if (s == "gui") { cout << gui; } else if (s == "backend") { cout << backend; } else { cout << "Unknown module '" << s << "' in the --help-module option\n"; return 1; } return 0; } if (vm.count("num-threads")) { cout << "The 'num-threads' options was set to " << vm["num-threads"].as<int>() << "\n"; } When parsing the command line, all options are allowed. The "--help" message, however, does not include the "Backend options" group -- the options in that group are hidden. The user can explicitly force the display of that options group by passing "--help-module backend" option. The complete example can be found in the "example/option_groups.cpp" file.
Custom Validators
By default, the conversion of option's value from string into C++ type is done using iostreams, which sometimes is not convenient. The library allows the user to customize the conversion for specific classes. In order to do so, the user should provide suitable overload of the validate function.
Let's first define a simple class: struct magic_number { public: magic_number(int n) : n(n) {} int n; }; and then overload the validate function: void validate(boost::any& v, const std::vector<std::string>& values, magic_number* target_type, int) { static regex r("\\d\\d\\d-(\\d\\d\\d)"); using namespace boost::program_options; // Make sure no previous assignment to 'a' was made. validators::check_first_occurence(v); // Extract the first string from 'values'. If there is more than // one string, it's an error, and exception will be thrown. const string& s = validators::get_single_string(values); // Do regex match and convert the interesting part to // int. smatch match; if (regex_match(s, match, r)) { v = any(magic_number(lexical_cast<int>(match[1]))); } else { throw validation_error("invalid value"); } } The function takes four parameters. The first is the storage for the value, and in this case is either empty or contains an instance of the magic_number class. The second is the list of strings found in the next occurrence of the option. The remaining two parameters are needed to workaround the lack of partial template specialization and partial function template ordering on some compilers.
The function first checks that we don't try to assign to the same option twice. Then it checks that only a single string was passed in. Next the string is verified with the help of the Boost.Regex library. If that test is passed, the parsed value is stored into the v variable.
The complete example can be found in the "example/regex.cpp" file.
Unicode Support
To use the library with Unicode, you'd need to: •Use Unicode-aware parsers for Unicode input•Require Unicode support for options which need it
Most of the parsers have Unicode versions. For example, the parse_command_line function has an overload which takes wchar_t strings, instead of ordinary char.
Even if some of the parsers are Unicode-aware, it does not mean you need to change definition of all the options. In fact, for many options, like integer ones, it makes no sense. To make use of Unicode you'll need some Unicode-aware options. They are different from ordinary options in that they accept wstring input, and process it using wide character streams. Creating an Unicode-aware option is easy: just use the the wvalue function instead of the regular value.
When an ascii parser passes data to an ascii option, or a Unicode parser passes data to a Unicode option, the data are not changed at all. So, the ascii option will see a string in local 8-bit encoding, and the Unicode option will see whatever string was passed as the Unicode input.
What happens when Unicode data is passed to an ascii option, and vice versa? The library automatically performs the conversion from Unicode to local 8-bit encoding. For example, if command line is in ascii, but you use wstring options, then the ascii input will be converted into Unicode.
To perform the conversion, the library uses the codecvt<wchar_t, char> locale facet from the global locale. If you want to work with strings that use local 8-bit encoding (as opposed to 7-bit ascii subset), your application should start with: locale::global(locale("")); which would set up the conversion facet according to the user's selected locale.
It's wise to check the status of the C++ locale support on your implementation, though. The quick test involves three steps: 1.Go the the "test" directory and build the "test_convert" binary.2.Set some non-ascii locale in the environmemt. On Linux, one can run, for example: $ export LC_CTYPE=ru_RU.KOI8-R 3.Run the "test_convert" binary with any non-ascii string in the selected encoding as its parameter. If you see a list of Unicode codepoints, everything's OK. Otherwise, locale support on your system might be broken.
Design Discussion
Design Discussion
This section focuses on some of the design questions.
Unicode Support
Unicode support was one of the features specifically requested during the formal review. Throughout this document "Unicode support" is a synonym for "wchar_t" support, assuming that "wchar_t" always uses Unicode encoding. Also, when talking about "ascii" (in lowercase) we'll not mean strict 7-bit ASCII encoding, but rather "char" strings in local 8-bit encoding.
Generally, "Unicode support" can mean many things, but for the program_options library it means that:

•
Each parser should accept either char* or wchar_t*, correctly split the input into option names and option values and return the data.
•
For each option, it should be possible to specify whether the conversion from string to value uses ascii or Unicode.
•
The library guarantees that: •ascii input is passed to an ascii value without change •Unicode input is passed to a Unicode value without change•ascii input passed to a Unicode value, and Unicode input passed to an ascii value will be converted using a codecvt facet (which may be specified by the user(which can be specified by the user)
The important point is that it's possible to have some "ascii options" together with "Unicode options". There are two reasons for this. First, for a given type you might not have the code to extract the value from Unicode string and it's not good to require that such code be written. Second, imagine a reusable library which has some options and exposes options description in its interface. If all options are either ascii or Unicode, and the library does not use any Unicode strings, then the author will likely to use ascii options, which would make the library unusable inside Unicode applications. Essentially, it would be necessary to provide two versions of the library -- ascii and Unicode.
Another important point is that ascii strings are passed though without modification. In other words, it's not possible to just convert ascii to Unicode and process the Unicode further. The problem is that the default conversion mechanism -- the codecvt facet -- might not work with 8-bit input without additional setup.
The Unicode support outlined above is not complete. For example, we don't plan allow Unicode in option names. Unicode support is hard and requires a Boost-wide solution. Even comparing two arbitrary Unicode strings is non-trivial. Finally, using Unicode in option names is related to internationalization, which has it's own complexities. E.g. if option names depend on current locale, then all program parts and other parts which use the name must be internationalized too.
The primary question in implementing the Unicode support is whether to use templates and std::basic_string or to use some internal encoding and convert between internal and external encodings on the interface boundaries.
The choice, mostly, is between code size and execution speed. A templated solution would either link library code into every application that uses the library (thereby making shared library impossible), or provide explicit instantiations in the shared library (increasing its size). The solution based on internal encoding would necessarily make conversions in a number of places and will be somewhat slower. Since speed is generally not an issue for this library, the second solution looks more attractive, but we'll take a closer look at individual components.
For the parsers component, we have three choices: •Use a fully templated implementation: given a string of a certain type, a parser will return a parsed_options instance with strings of the same type (i.e. the parsed_options class will be templated).•Use internal encoding: same as above, but strings will be converted to and from the internal encoding.•Use and partly expose the internal encoding: same as above, but the strings in the parsed_options instance will be in the internal encoding. This might avoid a conversion if parsed_options instance is passed directly to other components, but can be also dangerous or confusing for a user.
The second solution appears to be the best -- it does not increase the code size much and is cleaner than the third. To avoid extra conversions, the Unicode version of parsed_options can also store strings in internal encoding.
For the options descriptions component, we don't have much choice. Since it's not desirable to have either all options use ascii or all of them use Unicode, but rather have some ascii and some Unicode options, the interface of the value_semantic must work with both. The only way is to pass an additional flag telling if strings use ascii or internal encoding. The instance of value_semantic can then convert into some other encoding if needed.
For the storage component, the only affected function is store. For Unicode input, the store function should convert the value to the internal encoding. It should also inform the value_semantic class about the used encoding.
Finally, what internal encoding should we use? The alternatives are: std::wstring (using UCS-4 encoding) and std::string (using UTF-8 encoding). The difference between alternatives is: •Speed: UTF-8 is a bit slower•Space: UTF-8 takes less space when input is ascii•Code size: UTF-8 requires additional conversion code. However, it allows one to use existing parsers without converting them to std::wstring and such conversion is likely to create a number of new instantiations. There's no clear leader, but the last point seems important, so UTF-8 will be used.
Choosing the UTF-8 encoding allows the use of existing parsers, because 7-bit ascii characters retain their values in UTF-8, so searching for 7-bit strings is simple. However, there are two subtle issues: •We need to assume the character literals use ascii encoding and that inputs use Unicode encoding.•A Unicode character (say '=') can be followed by 'composing character' and the combination is not the same as just '=', so a simple search for '=' might find the wrong character. Neither of these issues appear to be critical in practice, since ascii is almost universal encoding and since composing characters following '=' (and other characters with special meaning to the library) are not likely to appear.
Acknowledgements
Acknowledgements
I'm very gratefull to all the people who helped with the development, by discussion, fixes, and as users. It was pleasant to see all that involvement, which made the library much better than it would be otherwise.
In the early stages, the library was affected by discussions with Gennadiy Rozental, William Kempf and Alexander Okhotin.
Hartmut Kaiser was the first person to try the library on his project and send a number of suggestions and fixes.
The formal review lead to numerous comments and enhancements. Pavol Droba helped with the option description semantic. Gennadiy Rozental has criticised many aspects of the library which caused various simplifications. Pavel Vozenilek did carefull review of the implementation. A number of comments were made by: •David Abrahams•Neal D. Becker•Misha Bergal•James Curran•Carl Daniel•Beman Dawes•Tanton Gibbs•Holger Grund•Hartmut Kaiser•Petr Kocmid•Baptiste Lepilleur•Marcelo E. Magallon•Chuck Messenger•John Torjo•Matthias Troyer
Doug Gregor and Reece Dunn helped to resolve the issues with Boostbook version of the documentation.
Even after review, a number of people have helped with further development: •Rob Lievaart•Thorsten Ottosen•Joseph Wu•Ferdinand Prantl•Miro Jurisic•John Maddock•Janusz Piwowarski•Charles Brockman•Jonathan Wakely
Reference
Reference
Header <boost/program_options/cmdline.hpp>
namespace
boost { namespace program_options { namespace command_line_style { enum style_t; } } }
Type style_t
Type style_t --
boost::program_options::command_line_style::style_t
enum
style_t { allow_long = 1, allow_short = allow_long << 1, allow_dash_for_short = allow_short << 1, allow_slash_for_short = allow_dash_for_short << 1, long_allow_adjacent = allow_slash_for_short << 1, long_allow_next = long_allow_adjacent << 1, short_allow_adjacent = long_allow_next << 1, short_allow_next = short_allow_adjacent << 1, allow_sticky = short_allow_next << 1, allow_guessing = allow_sticky << 1, case_insensitive = allow_guessing << 1, allow_long_disguise = case_insensitive << 1, unix_style = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_guessing | allow_dash_for_short), default_style = unix_style };
Header <boost/program_options/environment_iterator.hpp>
namespace
boost { class environment_iterator; }
Class environment_iterator
Class environment_iterator --
boost::environment_iterator
class
environment_iterator : public boost::eof_iterator< environment_iterator, std::pair< std::string, std::string > > { public: // construct/copy/destruct environment_iterator(char **); environment_iterator();

// public member functions
void
get
() ; };
Description
Description
environment_iterator construct/copy/destruct
environment_iterator
construct/copy/destruct
1.
environment_iterator(char ** environment);
2.
environment_iterator();
environment_iterator public member functions
environment_iterator
public member functions
1.
void
get() ;
Header <boost/program_options/eof_iterator.hpp>
namespace
boost { template<typename Derived, typename ValueType> class eof_iterator; }
Class template eof_iterator
Class template eof_iterator --
boost::eof_iterator
template
<typename Derived, typename ValueType> class eof_iterator { public: // construct/copy/destruct eof_iterator();

// public member functions
// protected member functions
ValueType & value() ; void found_eof() ;

// private member functions
void
increment
() ; bool equal(const eof_iterator &) const; const ValueType & dereference() const; };
Description
Description
The 'eof_iterator' class is useful for constructing forward iterators in cases where iterator extract data from some source and it's easy to detect 'eof' -- i.e. the situation where there's no data. One apparent example is reading lines from a file.
Implementing such iterators using 'iterator_facade' directly would require to create class with three core operation, a couple of constructors. When using 'eof_iterator', the derived class should define only one method to get new value, plus a couple of constructors.
The basic idea is that iterator has 'eof' bit. Two iterators are equal only if both have their 'eof' bits set. The 'get' method either obtains the new value or sets the 'eof' bit.
Specifically, derived class should define:
1. A default constructor, which creates iterator with 'eof' bit set. The constructor body should call 'found_eof' method defined here. 2. Some other constructor. It should initialize some 'data pointer' used in iterator operation and then call 'get'. 3. The 'get' method. It should operate this way:•look at some 'data pointer' to see if new element is available; if not, it should call 'found_eof'.•extract new element and store it at location returned by the 'value' method.•advance the data pointer.
Essentially, the 'get' method has the functionality of both 'increment' and 'dereference'. It's very good for the cases where data extraction implicitly moves data pointer, like for stream operation.
eof_iterator construct/copy/destruct
eof_iterator
construct/copy/destruct
1.
eof_iterator();
eof_iterator public member functions
eof_iterator
public member functions
eof_iterator protected member functions
eof_iterator
protected member functions
1.
ValueType & value() ;
Returns the reference which should be used by derived class to store the next value.
2.
void
found_eof() ;
Should be called by derived class to indicate that it can't produce next element.
eof_iterator private member functions
eof_iterator
private member functions
1.
void
increment() ;
2.
bool
equal(const eof_iterator & other) const;
3.
const
ValueType & dereference() const;
Header <boost/program_options/errors.hpp>
namespace
boost { namespace program_options { class error; class invalid_syntax; class unknown_option; class ambiguous_option; class multiple_values; class multiple_occurrences; class validation_error; class invalid_option_value; class too_many_positional_options_error; class too_few_positional_options_error; class invalid_command_line_syntax; class invalid_command_line_style; } }
Class error
Class error --
boost::program_options::error
class
error { public: // construct/copy/destruct error(const std::string &);

// public member functions
};
Description
Description
Base class for all errors in the library.
error construct/copy/destruct
error
construct/copy/destruct
1.
error(const std::string & what);
error public member functions
error
public member functions
Class invalid_syntax
Class invalid_syntax --
boost::program_options::invalid_syntax
class
invalid_syntax : public boost::program_options::error { public: // construct/copy/destruct invalid_syntax(const std::string &, const std::string &); ~invalid_syntax();

// public member functions

std::string tokens; std::string msg; };
Description
Description
invalid_syntax construct/copy/destruct
invalid_syntax
construct/copy/destruct
1.
invalid_syntax(const std::string & tokens, const std::string & msg);
2.
~invalid_syntax();
invalid_syntax public member functions
invalid_syntax
public member functions
Class unknown_option
Class unknown_option --
boost::program_options::unknown_option
class
unknown_option : public boost::program_options::error { public: // construct/copy/destruct unknown_option(const std::string &);

// public member functions
};
Description
Description
Class thrown when option name is not recognized.
unknown_option construct/copy/destruct
unknown_option
construct/copy/destruct
1.
unknown_option(const std::string & name);
unknown_option public member functions
unknown_option
public member functions
Class ambiguous_option
Class ambiguous_option --
boost::program_options::ambiguous_option
class
ambiguous_option : public boost::program_options::error { public: // construct/copy/destruct ambiguous_option(const std::string &, const std::vector< std::string > &); ~ambiguous_option();

// public member functions

std::vector< std::string > alternatives; };
Description
Description
Class thrown when there's ambiguity amoung several possible options.
ambiguous_option construct/copy/destruct
ambiguous_option
construct/copy/destruct
1.
ambiguous_option(const std::string & name, const std::vector< std::string > & alternatives);
2.
~ambiguous_option();
ambiguous_option public member functions
ambiguous_option
public member functions
Class multiple_values
Class multiple_values --
boost::program_options::multiple_values
class
multiple_values : public boost::program_options::error { public: // construct/copy/destruct multiple_values(const std::string &);

// public member functions
};
Description
Description
Class thrown when there are several option values, but user called a method which cannot return them all.
multiple_values construct/copy/destruct
multiple_values
construct/copy/destruct
1.
multiple_values(const std::string & what);
multiple_values public member functions
multiple_values
public member functions
Class multiple_occurrences
Class multiple_occurrences --
boost::program_options::multiple_occurrences
class
multiple_occurrences : public boost::program_options::error { public: // construct/copy/destruct multiple_occurrences(const std::string &);

// public member functions
};
Description
Description
Class thrown when there are several occurrences of an option, but user called a method which cannot return them all.
multiple_occurrences construct/copy/destruct
multiple_occurrences
construct/copy/destruct
1.
multiple_occurrences(const std::string & what);
multiple_occurrences public member functions
multiple_occurrences
public member functions
Class validation_error
Class validation_error --
boost::program_options::validation_error
class
validation_error : public boost::program_options::error { public: // construct/copy/destruct validation_error(const std::string &); ~validation_error();

// public member functions
void
set_option_name
(const std::string &) ;

// private member functions
const
char
* what() const; };
Description
Description
Class thrown when value of option is incorrect.
validation_error construct/copy/destruct
validation_error
construct/copy/destruct
1.
validation_error(const std::string & what);
2.
~validation_error();
validation_error public member functions
validation_error
public member functions
1.
void
set_option_name(const std::string & option) ;
validation_error private member functions
validation_error
private member functions
1.
const
char
* what() const;
Class invalid_option_value
Class invalid_option_value --
boost::program_options::invalid_option_value
class
invalid_option_value : : public boost::program_options::validation_error { public: // construct/copy/destruct invalid_option_value(const std::string &); invalid_option_value(const std::wstring &);

// public member functions
};
Description
Description
invalid_option_value construct/copy/destruct
invalid_option_value
construct/copy/destruct
1.
invalid_option_value(const std::string & value);
2.
invalid_option_value(const std::wstring & value);
invalid_option_value public member functions
invalid_option_value
public member functions
Class too_many_positional_options_error
Class too_many_positional_options_error --
boost::program_options::too_many_positional_options_error
class
too_many_positional_options_error : : public boost::program_options::error { public: // construct/copy/destruct too_many_positional_options_error(const std::string &);

// public member functions
};
Description
Description
Class thrown when there are too many positional options.
too_many_positional_options_error construct/copy/destruct
too_many_positional_options_error
construct/copy/destruct
1.
too_many_positional_options_error(const std::string & what);
too_many_positional_options_error public member functions
too_many_positional_options_error
public member functions
Class too_few_positional_options_error
Class too_few_positional_options_error --
boost::program_options::too_few_positional_options_error
class
too_few_positional_options_error : : public boost::program_options::error { public: // construct/copy/destruct too_few_positional_options_error(const std::string &);

// public member functions
};
Description
Description
Class thrown when there are too few positional options.
too_few_positional_options_error construct/copy/destruct
too_few_positional_options_error
construct/copy/destruct
1.
too_few_positional_options_error(const std::string & what);
too_few_positional_options_error public member functions
too_few_positional_options_error
public member functions
Class invalid_command_line_syntax
Class invalid_command_line_syntax --
boost::program_options::invalid_command_line_syntax
class
invalid_command_line_syntax { public: // construct/copy/destruct invalid_command_line_syntax(const std::string &, kind_t);

// public member functions
kind_t kind() const;

// protected static functions
std::string error_message(kind_t) ; };
Description
Description
invalid_command_line_syntax construct/copy/destruct
invalid_command_line_syntax
construct/copy/destruct
1.
invalid_command_line_syntax(const std::string & tokens, kind_t kind);
invalid_command_line_syntax public member functions
invalid_command_line_syntax
public member functions
1.
kind_t kind() const;
invalid_command_line_syntax protected static functions
invalid_command_line_syntax
protected static functions
1.
std::string error_message(kind_t kind) ;
Class invalid_command_line_style
Class invalid_command_line_style --
boost::program_options::invalid_command_line_style
class
invalid_command_line_style : public boost::program_options::error { public: // construct/copy/destruct invalid_command_line_style(const std::string &);

// public member functions
};
Description
Description
invalid_command_line_style construct/copy/destruct
invalid_command_line_style
construct/copy/destruct
1.
invalid_command_line_style(const std::string & msg);
invalid_command_line_style public member functions
invalid_command_line_style
public member functions
Header <boost/program_options/option.hpp>
namespace
boost { namespace program_options { template<typename charT> class basic_option;

typedef
basic_option
< char > option; typedef basic_option< wchar_t > woption; } }
Class template basic_option
Class template basic_option --
boost::program_options::basic_option
template
<typename charT> class basic_option { public: // construct/copy/destruct basic_option(); basic_option(const std::string &, const std::vector< std::string > &);

// public member functions

std::string string_key; int position_key; std::vector< std::basic_string< charT > > value; };
Description
Description
Option found in input source. Contains a key and a value. The key, in turn, can be a string (name of an option), or an integer (position in input source) -- in case no name is specified. The latter is only possible for command line. The template parameter specifies the type of char used for storing the option's value.
basic_option construct/copy/destruct
basic_option
construct/copy/destruct
1.
basic_option();
2.
basic_option(const std::string & string_key, const std::vector< std::string > & value);
basic_option public member functions
basic_option
public member functions
Header <boost/program_options/options_description.hpp>
namespace
boost { namespace program_options { class option_description; class options_description_easy_init; class options_description; class duplicate_option_error; } }
Class option_description
Class option_description --
boost::program_options::option_description
class
option_description { public: // construct/copy/destruct option_description(); option_description(const char *, const value_semantic *); option_description(const char *, const value_semantic *, const char *); ~option_description();

// public member functions
const
std::string & short_name() const; const std::string & long_name() const; const std::string & description() const; shared_ptr< const value_semantic > semantic() const; std::string format_name() const; std::string format_parameter() const;

// private member functions
option_description
& name(const char *) ; };
Description
Description
Describes one possible command line/config file option. There are two kinds of properties of an option. First describe it syntactically and are used only to validate input. Second affect interpretation of the option, for example default value for it or function that should be called when the value is finally known. Routines which perform parsing never use second kind of properties -- they are side effect free. options_description
option_description construct/copy/destruct
option_description
construct/copy/destruct
1.
option_description();
2.
option_description(const char * name, const value_semantic * s);
Initializes the object with the passed data.
Note: it would be nice to make the second parameter auto_ptr, to explicitly pass ownership. Unfortunately, it's often needed to create objects of types derived from 'value_semantic': options_description d; d.add_options()("a", parameter<int>("n")->default_value(1)); Here, the static type returned by 'parameter' should be derived from value_semantic.
Alas, derived->base conversion for auto_ptr does not really work, see http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/papers/2000/n1232.pdf http://std.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#84
So, we have to use plain old pointers. Besides, users are not expected to use the constructor directly.
The 'name' parameter is interpreted by the following rules:•if there's no "," character in 'name', it specifies long name•otherwise, the part before "," specifies long name and the part after -- long name.
3.
option_description(const char * name, const value_semantic * s, const char * description);
Initializes the class with the passed data.
4.
~option_description();
option_description public member functions
option_description
public member functions
1.
const
std::string & short_name() const;
2.
const
std::string & long_name() const;
3.
const
std::string & description() const;
4.
shared_ptr< const value_semantic > semantic() const;
5.
std::string format_name() const;
6.
std::string format_parameter() const;
Return the parameter name and properties, formatted suitably for usage message.
option_description private member functions
option_description
private member functions
1.
option_description
& name(const char * name) ;
Class options_description_easy_init
Class options_description_easy_init --
boost::program_options::options_description_easy_init
class
options_description_easy_init { public: // construct/copy/destruct options_description_easy_init(options_description *);

// public member functions
options_description_easy_init
& operator()(const char *, const char *) ; options_description_easy_init & operator()(const char *, const value_semantic *) ; options_description_easy_init & operator()(const char *, const value_semantic *, const char *) ; };
Description
Description
Class which provides convenient creation syntax to option_description.
options_description_easy_init construct/copy/destruct
options_description_easy_init
construct/copy/destruct
1.
options_description_easy_init(options_description * owner);
options_description_easy_init public member functions
options_description_easy_init
public member functions
1.
options_description_easy_init
& operator()(const char * name, const char * description) ;
2.
options_description_easy_init
& operator()(const char * name, const value_semantic * s) ;
3.
options_description_easy_init
& operator()(const char * name, const value_semantic * s, const char * description) ;
Class options_description
Class options_description --
boost::program_options::options_description
class
options_description { public: // construct/copy/destruct options_description(); options_description(const std::string &);

// public member functions
void
add
(shared_ptr< option_description >) ; options_description & add(const options_description &) ; options_description_easy_init add_options() ; unsigned count(const std::string &) const; unsigned count_approx(const std::string &) const; const option_description & find(const std::string &) const; const option_description & find_approx(const std::string &) const; std::set< std::string > keys() const; std::set< std::string > primary_keys() const; std::set< std::string > approximations(const std::string &) const; void print(std::ostream &) const;

// private member functions
approximation_range find_approximation(const std::string &) const; };
Description
Description
A set of option descriptions. This provides convenient interface for adding new option (the add_options) method, and facilities to search for options by name.
See here for option adding interface discussion. option_description
options_description construct/copy/destruct
options_description
construct/copy/destruct
1.
options_description();
Creates the instance.
2.
options_description(const std::string & caption);
Creates the instance. The 'caption' parameter gives the name of this 'options_description' instance. Primarily useful for output.
options_description public member functions
options_description
public member functions
1.
void
add(shared_ptr< option_description > desc) ;
Adds new variable description. Throws duplicate_variable_error if either short or long name matches that of already present one.
2.
options_description
& add(const options_description & desc) ;
Adds a group of option description. This has the same effect as adding all option_descriptions in 'desc' individually, except that output operator will show a separate group. Returns *this.
3.
options_description_easy_init
add_options() ;
Returns an object of implementation-defined type suitable for adding options to options_description. The returned object will have overloaded operator() with parameter type matching 'option_description' constructors. Calling the operator will create new option_description instance and add it.
4.
unsigned
count(const std::string & name) const;
Count the number of option descriptions with given name. Returns 0 or 1. The 'name' parameter can be either name of long option, and short option prefixed by '-'.
5.
unsigned
count_approx(const std::string & prefix) const;
Count the number of descriptions having the given string as prefix. This makes sense only for long options.
6.
const
option_description
& find(const std::string & name) const;
Returns description given a name.
Requires
count(name) == 1
7.
const
option_description
& find_approx(const std::string & prefix) const;
Returns description given a prefix. Throws
Requires
count_approx(name) == 1
8.
std::set< std::string > keys() const;
9.
std::set< std::string > primary_keys() const;
For each option description stored, contains long name if not empty, if it is empty, short name is returned.
10.
std::set< std::string > approximations(const std::string & prefix) const;
11.
void
print(std::ostream & os) const;
Output 'desc' to the specified stream, calling 'f' to output each option_description element.
options_description private member functions
options_description
private member functions
1.
approximation_range find_approximation(const std::string & prefix) const;
Class duplicate_option_error
Class duplicate_option_error --
boost::program_options::duplicate_option_error
class
duplicate_option_error : public boost::program_options::error { public: // construct/copy/destruct duplicate_option_error(const std::string &);

// public member functions
};
Description
Description
Class thrown when duplicate option description is found.
duplicate_option_error construct/copy/destruct
duplicate_option_error
construct/copy/destruct
1.
duplicate_option_error(const std::string & what);
duplicate_option_error public member functions
duplicate_option_error
public member functions
Header <boost/program_options/parsers.hpp>
namespace
boost { namespace program_options { template<typename charT> class basic_parsed_options;

template
<> class basic_parsed_options<wchar_t>;

class
common_command_line_parser
; template<typename charT> class basic_command_line_parser;

typedef
basic_parsed_options
< char > parsed_options; typedef basic_parsed_options< wchar_t > wparsed_options; typedef function1< std::pair< std::string, std::string >, const std::string & > ext_parser; typedef basic_command_line_parser< char > command_line_parser; typedef basic_command_line_parser< wchar_t > wcommand_line_parser; template<typename charT> basic_parsed_options< charT > parse_command_line(int, charT *, const options_description &, int = 0, function1< std::pair< std::string, std::string >, const std::string & > = ext_parser()); template<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(std::basic_istream< charT > &, const options_description &); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const function1< std::string, std::string > &); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const std::string &); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const char *); } }
Class template basic_parsed_options
Class template basic_parsed_options --
boost::program_options::basic_parsed_options
template
<typename charT> class basic_parsed_options { public: // construct/copy/destruct basic_parsed_options(const options_description *);

// public member functions

std::vector< basic_option< charT > > options; const options_description * description; };
Description
Description
Results of parsing an input source. The primary use of this class is passing information from parsers component to value storage component. This class does not makes much sense itself.
basic_parsed_options construct/copy/destruct
basic_parsed_options
construct/copy/destruct
1.
basic_parsed_options(const options_description * description);
basic_parsed_options public member functions
basic_parsed_options
public member functions
Specializations
Specializations
•
Class basic_parsed_options<wchar_t>
Class basic_parsed_options<wchar_t>
Class basic_parsed_options<wchar_t> --
boost::program_options::basic_parsed_options<wchar_t>
class
basic_parsed_options<wchar_t> { public:

// public member functions
basic_parsed_options
(const basic_parsed_options< char > &) ;

std::vector< basic_option< wchar_t > > options; const options_description * description; basic_parsed_options< char > utf8_encoded_options; };
Description
Description
Specialization of basic_parsed_options which:•provides convenient conversion from basic_parsed_options<char>•stores the passed char-based options for later use.
basic_parsed_options public member functions
basic_parsed_options
public member functions
1.
basic_parsed_options(const basic_parsed_options< char > & po) ;
Constructs wrapped options from options in UTF8 encoding.
Class common_command_line_parser
Class common_command_line_parser --
boost::program_options::common_command_line_parser
class
common_command_line_parser { public: // construct/copy/destruct common_command_line_parser(const std::vector< std::string > &);

// public member functions
parsed_options run() const; };
Description
Description
Character-type independent command line parser.
common_command_line_parser construct/copy/destruct
common_command_line_parser
construct/copy/destruct
1.
common_command_line_parser(const std::vector< std::string > & args);
common_command_line_parser public member functions
common_command_line_parser
public member functions
1.
parsed_options run() const;
Parses the command line and returns parsed options in internal encoding.
Class template basic_command_line_parser
Class template basic_command_line_parser --
boost::program_options::basic_command_line_parser
template
<typename charT> class basic_command_line_parser : : private boost::program_options::common_command_line_parser { public: // construct/copy/destruct basic_command_line_parser(const std::vector< std::basic_string< charT > > &); basic_command_line_parser(int, charT *);

// public member functions
basic_command_line_parser
& options(const options_description &) ; basic_command_line_parser & positional(const positional_options_description &) ; basic_command_line_parser & style(int) ; basic_command_line_parser & extra_parser(ext_parser) ; basic_parsed_options< charT > run() const; };
Description
Description
Command line parser.
The class allows one to specify all the information needed for parsing and to parser the parse the command line. It is primarily needed to emulate named function parameters -- a regular function with 5 parameters will be hard to use and creating overloads with a smaller nuber of parameters will be confusing.
For the most common case, the function parse_command_line is a better alternative.
basic_command_line_parser construct/copy/destruct
basic_command_line_parser
construct/copy/destruct
1.
basic_command_line_parser(const std::vector< std::basic_string< charT > > & args);
Creates a command line parser for the specified arguments list. The 'args' parameter should not include program name.
2.
basic_command_line_parser(int argc, charT * argv);
Creates a command line parser for the specified arguments list. The parameter should be the same as passes to 'main'.
basic_command_line_parser public member functions
basic_command_line_parser
public member functions
1.
basic_command_line_parser
& options(const options_description & desc) ;
Sets options descriptions to use.
2.
basic_command_line_parser
& positional(const positional_options_description & desc) ;
Sets positional options description to use.
3.
basic_command_line_parser
& style(int ) ;
Sets the command line style.
4.
basic_command_line_parser
& extra_parser(ext_parser ) ;
Sets the extra parsers.
5.
basic_parsed_options
< charT > run() const;
Parses the command line and returns parsed options in internal encoding.
Function template parse_command_line
Function template parse_command_line --
boost::program_options::parse_command_line
template
<typename charT> basic_parsed_options< charT > parse_command_line(int argc, charT * argv, const options_description & , int style = 0, function1< std::pair< std::string, std::string >, const std::string & > ext = ext_parser());
Description
Description
Creates instance of 'command_line_parser', passes parameters to it, and returns the result of calling the 'run' method.
Function template parse_config_file
Function template parse_config_file --
boost::program_options::parse_config_file
template
<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(std::basic_istream< charT > & , const options_description & );
Description
Description
Parse a config file.
Function parse_environment
Function parse_environment --
boost::program_options::parse_environment
BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description & , const function1< std::string, std::string > & name_mapper);
Description
Description
Parse environment.
For each environment variable, the 'name_mapper' function is called to obtain the option name. If it returns empty string, the variable is ignored.
This is done since naming of environment variables is typically different from the naming of command line options.
Function parse_environment
Function parse_environment --
boost::program_options::parse_environment
BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description & , const std::string & prefix); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description & , const char * prefix);
Description
Description
Parse environment.
Takes all environment variables which start with 'prefix'. The option name is obtained from variable name by removing the prefix and converting the remaining string into lower case.
Header <boost/program_options/positional_options.hpp>
namespace
boost { namespace program_options { class positional_options_description; } }
Class positional_options_description
Class positional_options_description --
boost::program_options::positional_options_description
class
positional_options_description { public: // construct/copy/destruct positional_options_description();

// public member functions
void
add
(const char *, int) ; unsigned max_total_count() const; const std::string & name_for_position(unsigned) const; };
Description
Description
Describes positional options.
The class allows to guess option names for positional options, which are specified on the command line and are identified by the position. The class uses the information provided by the user to associate a name with every positional option, or tell that no name is known.
The primary assumption is that only the relative order of the positional options themselves matters, and that any interleaving ordinary options don't affect interpretation of positional options.
The user initializes the class by specifying that first N positional options should be given the name X1, following M options should be given the name X2 and so on.
positional_options_description construct/copy/destruct
positional_options_description
construct/copy/destruct
1.
positional_options_description();
positional_options_description public member functions
positional_options_description
public member functions
1.
void
add(const char * name, int max_count) ;
Species that up to 'max_count' next positional options should be given the 'name'. The value of '-1' means 'unlimited'. No calls to 'add' can be made after call with 'max_value' equal to '-1'.
2.
unsigned
max_total_count() const;
Returns the maximum number of positional options that can be present. Can return numeric_limits<unsigned>::max() to indicate unlimited number.
3.
const
std::string & name_for_position(unsigned position) const;
Returns the name that should be associated with positional options at 'position'. Precondition: position < max_total_count()
Header <boost/program_options/value_semantic.hpp>
namespace
boost { namespace program_options { class value_semantic; template<typename charT> class value_semantic_codecvt_helper;

template
<> class value_semantic_codecvt_helper<char>; template<> class value_semantic_codecvt_helper<wchar_t>;

class
untyped_value
; template<typename T, typename charT = char> class typed_value; template<typename T> typed_value< T > * value(); template<typename T> typed_value< T > * value(T *); template<typename T> typed_value< T, wchar_t > * wvalue(); template<typename T> typed_value< T, wchar_t > * wvalue(T *); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(bool *); } }
Class value_semantic
Class value_semantic --
boost::program_options::value_semantic
class
value_semantic { public: // construct/copy/destruct ~value_semantic();

// public member functions
virtual
std::string name() const; virtual bool is_zero_tokens() const; virtual bool is_composing() const; virtual bool is_implicit() const; virtual bool is_multitoken() const; virtual void parse(boost::any &, const std::vector< std::string > &, bool) const; virtual bool apply_default(boost::any &) const; virtual void notify(const boost::any &) const; };
Description
Description
Class which specifies how the option's value is to be parsed and converted into C++ types.
value_semantic construct/copy/destruct
value_semantic
construct/copy/destruct
1.
~value_semantic();
value_semantic public member functions
value_semantic
public member functions
1.
virtual
std::string name() const;
Returns the name of the option. The name is only meaningful for automatic help message.
2.
virtual
bool
is_zero_tokens() const;
Returns true if value cannot be specified in source at all. Other methods can still set the value somehow, but user can't affect it.
3.
virtual
bool
is_composing() const;
Returns true if values from different sources should be composed. Otherwise, value from the first source is used and values from other sources are discarded.
4.
virtual
bool
is_implicit() const;
Returns true if explicit value of an option can be omitted.
5.
virtual
bool
is_multitoken() const;
Returns true if value can span several token in input source.
6.
virtual
void
parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specified more than once.
7.
virtual
bool
apply_default(boost::any & value_store) const;
Called to assign default value to 'value_store'. Returns true if default value is assigned, and false if no default value exists.
8.
virtual
void
notify(const boost::any & value_store) const;
Called when final value of an option is determined.
Class template value_semantic_codecvt_helper
Class template value_semantic_codecvt_helper --
boost::program_options::value_semantic_codecvt_helper
template
<typename charT> class value_semantic_codecvt_helper { public: };
Description
Description
Helper class which perform necessary character conversions in the 'parse' method and forwards the data further.
Specializations
Specializations
•
Class value_semantic_codecvt_helper<char>
•
Class value_semantic_codecvt_helper<wchar_t>
Class value_semantic_codecvt_helper<char>
Class value_semantic_codecvt_helper<char> --
boost::program_options::value_semantic_codecvt_helper<char>
class
value_semantic_codecvt_helper<char> { public:

// protected member functions
virtual
void
xparse
(boost::any &, const std::vector< std::string > &) const;

// private member functions
void
parse
(boost::any &, const std::vector< std::string > &, bool) const; };
Description
Description
value_semantic_codecvt_helper protected member functions
value_semantic_codecvt_helper
protected member functions
1.
virtual
void
xparse(boost::any & value_store, const std::vector< std::string > & new_tokens) const;
value_semantic_codecvt_helper private member functions
value_semantic_codecvt_helper
private member functions
1.
void
parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Class value_semantic_codecvt_helper<wchar_t>
Class value_semantic_codecvt_helper<wchar_t> --
boost::program_options::value_semantic_codecvt_helper<wchar_t>
class
value_semantic_codecvt_helper<wchar_t> : : public boost::program_options::value_semantic { public:

// protected member functions
virtual
void
xparse
(boost::any &, const std::vector< std::wstring > &) const;

// private member functions
void
parse
(boost::any &, const std::vector< std::string > &, bool) const; };
Description
Description
value_semantic_codecvt_helper protected member functions
value_semantic_codecvt_helper
protected member functions
1.
virtual
void
xparse(boost::any & value_store, const std::vector< std::wstring > & new_tokens) const;
value_semantic_codecvt_helper private member functions
value_semantic_codecvt_helper
private member functions
1.
void
parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Class untyped_value
Class untyped_value --
boost::program_options::untyped_value
class
untyped_value : : public boost::program_options::value_semantic_codecvt_helper< charT > { public: // construct/copy/destruct untyped_value(bool = false);

// public member functions
std::string name() const; bool is_zero_tokens() const; bool is_composing() const; bool is_implicit() const; bool is_multitoken() const; void xparse(boost::any &, const std::vector< std::string > &) const; bool apply_default(boost::any &) const; void notify(const boost::any &) const; };
Description
Description
Class which specifies a simple handling of a value: the value will have string type and only one token is allowed.
untyped_value construct/copy/destruct
untyped_value
construct/copy/destruct
1.
untyped_value(bool zero_tokens = false);
untyped_value public member functions
untyped_value
public member functions
1.
std::string name() const;
2.
bool
is_zero_tokens() const;
3.
bool
is_composing() const;
4.
bool
is_implicit() const;
5.
bool
is_multitoken() const;
6.
void
xparse(boost::any & value_store, const std::vector< std::string > & new_tokens) const;
If 'value_store' is already initialized, or new_tokens has more than one elements, throws. Otherwise, assigns the first string from 'new_tokens' to 'value_store', without any modifications.
7.
bool
apply_default(boost::any & ) const;
Does nothing.
8.
void
notify(const boost::any & ) const;
Does nothing.
Class template typed_value
Class template typed_value --
boost::program_options::typed_value
template
<typename T, typename charT = char> class typed_value : : public boost::program_options::value_semantic_codecvt_helper< charT > { public: // construct/copy/destruct typed_value(T *);

// public member functions
typed_value
* default_value(const T &) ; typed_value * default_value(const T &, const std::string &) ; typed_value * notifier(function1< void, const T & >) ; typed_value * composing() ; typed_value * implicit() ; typed_value * multitoken() ; typed_value * zero_tokens() ; std::string name() const; bool is_zero_tokens() const; bool is_composing() const; bool is_implicit() const; bool is_multitoken() const; void xparse(boost::any &, const std::vector< std::basic_string< charT > > &) const; virtual bool apply_default(boost::any &) const; void notify(const boost::any &) const; };
Description
Description
Class which handles value of a specific type.
typed_value construct/copy/destruct
typed_value
construct/copy/destruct
1.
typed_value(T * store_to);
Ctor. The 'store_to' parameter tells where to store the value when it's known. The parameter can be NULL.
typed_value public member functions
typed_value
public member functions
1.
typed_value
* default_value(const T & v) ;
Specifies default value, which will be used if none is explicitly specified. The type 'T' should provide operator<< for ostream.
2.
typed_value
* default_value(const T & v, const std::string & textual) ;
Specifies default value, which will be used if none is explicitly specified. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user.
3.
typed_value
* notifier(function1< void, const T & > f) ;
Specifies a function to be called when the final value is determined.
4.
typed_value
* composing() ;
Specifies that the value is composing. See the 'is_composing' method for explanation.
5.
typed_value
* implicit() ;
Specifies that the value is implicit.
6.
typed_value
* multitoken() ;
Specifies that the value can span multiple tokens.
7.
typed_value
* zero_tokens() ;
8.
std::string name() const;
9.
bool
is_zero_tokens() const;
10.
bool
is_composing() const;
11.
bool
is_implicit() const;
12.
bool
is_multitoken() const;
13.
void
xparse(boost::any & value_store, const std::vector< std::basic_string< charT > > & new_tokens) const;
Creates an instance of the 'validator' class and calls its operator() to perform athe ctual conversion.
14.
virtual
bool
apply_default(boost::any & value_store) const;
If default value was specified via previous call to 'default_value', stores that value into 'value_store'. Returns true if default value was stored.
15.
void
notify(const boost::any & value_store) const;
If an address of variable to store value was specified when creating *this, stores the value there. Otherwise, does nothing.
Function value
Function value --
boost::program_options::value
template
<typename T> typed_value< T > * value(); template<typename T> typed_value< T > * value(T * v);
Description
Description
Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor. The second overload is used when it's additionally desired to store the value of option into program variable.
Function wvalue
Function wvalue --
boost::program_options::wvalue
template
<typename T> typed_value< T, wchar_t > * wvalue(); template<typename T> typed_value< T, wchar_t > * wvalue(T * v);
Description
Description
Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor.
Function bool_switch
Function bool_switch --
boost::program_options::bool_switch
BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(bool * v);
Description
Description
Works the same way as the 'value<bool>' function, but the created value_semantic won't accept any explicit value. So, if the option is present on the command line, the value will be 'true'.
Header <boost/program_options/variables_map.hpp>
namespace
boost { namespace program_options { class variable_value; class abstract_variables_map; class variables_map; BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > &, variables_map &, bool = false); BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< wchar_t > &, variables_map &); BOOST_PROGRAM_OPTIONS_DECL void notify(variables_map &); } }
Class variable_value
Class variable_value --
boost::program_options::variable_value
class
variable_value { public: // construct/copy/destruct variable_value(); variable_value(const boost::any &, bool);

// public member functions
template
<typename T> const T & as() const; template<typename T> T & as() ; bool empty() const; bool defaulted() const; const boost::any & value() const; boost::any & value() ; };
Description
Description
Class holding value of option. Contains details about how the value is set and allows to conveniently obtain the value.
variable_value construct/copy/destruct
variable_value
construct/copy/destruct
1.
variable_value();
2.
variable_value(const boost::any & v, bool defaulted);
variable_value public member functions
variable_value
public member functions
1.
template
<typename T> const T & as() const;
If stored value if of type T, returns that value. Otherwise, throws boost::bad_any_cast exception.
2.
template
<typename T> T & as() ;
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
3.
bool
empty() const;
4.
bool
defaulted() const;
Returns true if the value was not explicitly given, but has default value.
5.
const
boost::any & value() const;
Returns the contained value.
6.
boost::any & value() ;
Returns the contained value.
Class abstract_variables_map
Class abstract_variables_map --
boost::program_options::abstract_variables_map
class
abstract_variables_map { public: // construct/copy/destruct abstract_variables_map(); abstract_variables_map(const abstract_variables_map *); ~abstract_variables_map();

// public member functions
const
variable_value
& operator[](const std::string &) const; void next(abstract_variables_map *) ;

// private member functions
virtual
const
variable_value
& get(const std::string &) const; };
Description
Description
Implements string->string mapping with convenient value casting facilities.
abstract_variables_map construct/copy/destruct
abstract_variables_map
construct/copy/destruct
1.
abstract_variables_map();
2.
abstract_variables_map(const abstract_variables_map * next);
3.
~abstract_variables_map();
abstract_variables_map public member functions
abstract_variables_map
public member functions
1.
const
variable_value
& operator[](const std::string & name) const;
Obtains the value of variable 'name', from *this and possibly from the chain of variable maps.
•
if there's no value in *this.•if there's next variable map, returns value from it•otherwise, returns empty value
•
if there's defaulted value•if there's next varaible map, which has a non-defauled value, return that•otherwise, return value from *this
•
if there's a non-defauled value, returns it.
2.
void
next(abstract_variables_map * next) ;
Sets next variable map, which will be used to find variables not found in *this.
abstract_variables_map private member functions
abstract_variables_map
private member functions
1.
virtual
const
variable_value
& get(const std::string & name) const;
Returns value of variable 'name' stored in *this, or empty value otherwise.
Class variables_map
Class variables_map --
boost::program_options::variables_map
class
variables_map : : public boost::program_options::abstract_variables_map { public: // construct/copy/destruct variables_map(); variables_map(const abstract_variables_map *);

// public member functions
const
variable_value
& operator[](const std::string &) const;

// private member functions
const
variable_value
& get(const std::string &) const; };
Description
Description
Concrete variables map which store variables in real map.
variables_map construct/copy/destruct
variables_map
construct/copy/destruct
1.
variables_map();
2.
variables_map(const abstract_variables_map * next);
variables_map public member functions
variables_map
public member functions
1.
const
variable_value
& operator[](const std::string & name) const;
Obtains the value of variable 'name', from *this and possibly from the chain of variable maps.
•
if there's no value in *this.•if there's next variable map, returns value from it•otherwise, returns empty value
•
if there's defaulted value•if there's next varaible map, which has a non-defauled value, return that•otherwise, return value from *this
•
if there's a non-defauled value, returns it.
variables_map private member functions
variables_map
private member functions
1.
const
variable_value
& get(const std::string & name) const;
Implementation of abstract_variables_map::get which does 'find' in *this.
Function store
Function store --
boost::program_options::store
BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > & options, variables_map & m, bool utf8 = false);
Description
Description
Stores in 'm' all options that are defined in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value.
Function store
Function store --
boost::program_options::store
BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< wchar_t > & options, variables_map & m);
Description
Description
Stores in 'm' all options that are defined in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value. This is wide character variant.
Function notify
Function notify --
boost::program_options::notify
BOOST_PROGRAM_OPTIONS_DECL void notify(variables_map & m);
Description
Description
Runs all 'notify' function for options in 'm'.
Header <boost/program_options/version.hpp>
BOOST_PROGRAM_OPTIONS_VERSION
Macro BOOST_PROGRAM_OPTIONS_VERSION
Macro BOOST_PROGRAM_OPTIONS_VERSION --
BOOST_PROGRAM_OPTIONS_VERSION
BOOST_PROGRAM_OPTIONS_VERSION
Description
Description
The version of the source interface. The value will be incremented whenever a change is made which might cause compilation errors for existing code.

Boost.Ref

Boost.Ref

Boost.Ref
Jaakko Järvi
Peter Dimov
Douglas Gregor
Dave Abrahams
Copyright © 1999, 2000 Jaakko Järvi
Copyright © 2001, 2002 Peter Dimov
Copyright © 2002 David Abrahams
Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.
Introduction
Introduction
The Ref library is a small library that is useful for passing references to function templates (algorithms) that would usually take copies of their arguments. It defines the class template boost::reference_wrapper<T>, the two functions boost::ref and boost::cref that return instances of boost::reference_wrapper<T>, and the two traits classes boost::is_reference_wrapper<T> and boost::unwrap_reference<T>.
The purpose of boost::reference_wrapper<T> is to contain a reference to an object of type T. It is primarily used to "feed" references to function templates (algorithms) that take their parameter by value.
To support this usage, boost::reference_wrapper<T> provides an implicit conversion to T&. This usually allows the function templates to work on references unmodified.
boost::reference_wrapper<T>
is both CopyConstructible and Assignable (ordinary references are not Assignable).
The expression boost::ref(x) returns a boost::reference_wrapper<X>(x) where X is the type of x. Similarly, boost::cref(x) returns a boost::reference_wrapper<X const>(x).
The expression boost::is_reference_wrapper<T>::value is true if T is a reference_wrapper, and false otherwise.
The type-expression boost::unwrap_reference<T>::type is T::type if T is a reference_wrapper, T otherwise.
Reference
Reference
Header <boost/ref.hpp>
namespace
boost { template<typename T> class reference_wrapper; reference_wrapper<T> ref(T&); reference_wrapper<T const> cref(T const&); template<typename T> class is_reference_wrapper; template<typename T> class unwrap_reference; }
Class template reference_wrapper
Class template reference_wrapper -- Contains a reference to an object of type T.
boost::reference_wrapper
template
<typename T> class reference_wrapper { public: // types typedef T type;

// construct/copy/destruct
explicit
reference_wrapper
(T&);

// access
operator
T&
() const; T& get() const; T* get_pointer() const; };

// constructors
reference_wrapper<T> ref(T&); reference_wrapper<T const> cref(T const&);
Description
Description
reference_wrapper
is primarily used to "feed" references to function templates (algorithms) that take their parameter by value. It provides an implicit conversion to T&, which usually allows the function templates to work on references unmodified.
reference_wrapper construct/copy/destruct
reference_wrapper
construct/copy/destruct
1.
explicit
reference_wrapper(T& t);
Effects
Constructs a reference_wrapper object that stores a reference to t.
Throws
Does not throw.
reference_wrapper access
reference_wrapper
access
1.
operator
T&() const;
Returns
The stored reference.
Throws
Does not throw.
2.
T& get() const;
Returns
The stored reference.
Throws
Does not throw.
3.
T* get_pointer() const;
Returns
A pointer to the object referenced by the stored reference.
Throws
Does not throw.
reference_wrapper constructors
reference_wrapper
constructors
1.
reference_wrapper<T> ref(T& t);
Returns
reference_wrapper
<T>(t)
Throws
Does not throw.
2.
reference_wrapper<T const> cref(T const& t);
Returns
reference_wrapper
<T const>(t)
Throws
Does not throw.
Class template is_reference_wrapper
Class template is_reference_wrapper -- Determine if a type T is an instantiation of reference_wrapper.
boost::is_reference_wrapper
template
<typename T> class is_reference_wrapper { public: // static constants static const bool value = unspecified; };
Description
Description
The value static constant will be true iff the type T is a specialization of reference_wrapper.
Class template unwrap_reference
Class template unwrap_reference -- Find the type in a reference_wrapper.
boost::unwrap_reference
template
<typename T> class unwrap_reference { public: // types typedef unspecified type; };
Description
Description
The typedef type is T::type if T is a reference_wrapper, T otherwise.
Acknowledgements
Acknowledgements
ref
and cref were originally part of the Tuple library by Jaakko Järvi. They were "promoted to boost:: status" by Peter Dimov because they are generally useful. Douglas Gregor and Dave Abrahams contributed is_reference_wrapper and unwrap_reference.

Boost.Signals

Boost.Signals

Boost.Signals
Douglas Gregor
Copyright © 2001-2004 Douglas Gregor
Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
The Boost.Signals library is an implementation of a managed signals and slots system. Signals represent callbacks with multiple targets, and are also called publishers or events in similar systems. Signals are connected to some set of slots, which are callback receivers (also called event targets or subscribers), which are called when the signal is "emitted."
Signals and slots are managed, in that signals and slots (or, more properly, objects that occur as part of the slots) track all connections and are capable of automatically disconnecting signal/slot connections when either is destroyed. This enables the user to make signal/slot connections without expending a great effort to manage the lifetimes of those connections with regard to the lifetimes of all objects involved.
When signals are connected to multiple slots, there is a question regarding the relationship between the return values of the slots and the return value of the signals. Boost.Signals allows the user to specify the manner in which multiple return values are combined.
Tutorial
Tutorial
How to Read this Tutorial
This tutorial is not meant to be read linearly. Its top-level structure roughly separates different concepts in the library (e.g., handling calling multiple slots, passing values to and from slots) and in each of these concepts the basic ideas are presented first and then more complex uses of the library are described later. Each of the sections is marked Beginner, Intermediate, or Advanced to help guide the reader. The Beginner sections include information that all library users should know; one can make good use of the Signals library after having read only the Beginner sections. The Intermediate sections build on the Beginner sections with slightly more complex uses of the library. Finally, the Advanced sections detail very advanced uses of the Signals library, that often require a solid working knowledge of the Beginner and Intermediate topics; most users will not need to read the Advanced sections.
Compatibility Note
Boost.Signals has two syntactical forms: the preferred form and the compatibility form. The preferred form fits more closely with the C++ language and reduces the number of separate template parameters that need to be considered, often improving readability; however, the preferred form is not supported on all platforms due to compiler bugs. The compatible form will work on all compilers supported by Boost.Signals. Consult the table below to determine which syntactic form to use for your compiler. Users of Boost.Function, please note that the preferred syntactic form in Signals is equivalent to that of Function's preferred syntactic form.
If your compiler does not appear in this list, please try the preferred syntax and report your results to the Boost list so that we can keep this table up-to-date.

Preferred syntax
Portable syntax
•
GNU C++ 2.95.x, 3.0.x, 3.1.x
•
Comeau C++ 4.2.45.2
•
SGI MIPSpro 7.3.0
•
Intel C++ 5.0, 6.0
•
Compaq's cxx 6.2
•
Microsoft Visual C++ 7.1
•
Any compiler supporting the preferred syntax
•
Microsoft Visual C++ 6.0, 7.0
•
Borland C++ 5.5.1
•
Sun WorkShop 6 update 2 C++ 5.3
•
Metrowerks CodeWarrior 8.1

Hello, World! (Beginner)
The following example writes "Hello, World!" using signals and slots. First, we create a signal sig, a signal that takes no arguments and has a void return value. Next, we connect the hello function object to the signal using the connect method. Finally, use the signal sig like a function to call the slots, which in turns invokes HelloWorld::operator() to print "Hello, World!".

Preferred syntax
Portable syntax
struct HelloWorld { void operator()() const { std::cout << "Hello, World!" << std::endl; } };

// ...

// Signal with no arguments and a void return value boost::signal<void ()> sig;

// Connect a HelloWorld slot HelloWorld hello; sig.connect(hello);

// Call all of the slots sig();
struct HelloWorld { void operator()() const { std::cout << "Hello, World!" << std::endl; } };

// ...

// Signal with no arguments and a void return value boost::signal0<void> sig;

// Connect a HelloWorld slot HelloWorld hello; sig.connect(hello);

// Call all of the slots sig();

Calling multiple slots
Connecting multiple slots (Beginner)
Calling a single slot from a signal isn't very interesting, so we can make the Hello, World program more interesting by splitting the work of printing "Hello, World!" into two completely separate slots. The first slot will print "Hello" and may look like this:
struct Hello { void operator()() const { std::cout << "Hello"; } };
The second slot will print ", World!" and a newline, to complete the program. The second slot may look like this:
struct World { void operator()() const { std::cout << ", World!" << std::endl; } };
Like in our previous example, we can create a signal sig that takes no arguments and has a void return value. This time, we connect both a hello and a world slot to the same signal, and when we call the signal both slots will be called.

Preferred syntax
Portable syntax
boost::signal
<void ()> sig;

sig.connect(Hello()); sig.connect(World());

sig();
boost::signal0
<void> sig;

sig.connect(Hello()); sig.connect(World());

sig();

By default, slots are called in first-in first-out (FIFO) order, so the output of this program will be as expected:
Hello, World!
Ordering slot call groups (Intermediate)
Slots are free to have side effects, and that can mean that some slots will have to be called before others even if they are not connected in that order. The Boost.Signals library allows slots to be placed into groups that are ordered in some way. For our Hello, World program, we want "Hello" to be printed before ", World!", so we put "Hello" into a group that must be executed before the group that ", World!" is in. To do this, we can supply an extra parameter at the beginning of the connect call that specifies the group. Group values are, by default, ints, and are ordered by the integer < relation. Here's how we construct Hello, World:

Preferred syntax
Portable syntax
boost::signal
<void ()> sig; sig.connect(1, World()); sig.connect(0, Hello()); sig();
boost::signal0
<void> sig; sig.connect(1, World()); sig.connect(0, Hello()); sig();

This program will correctly print "Hello, World!", because the Hello object is in group 0, which precedes group 1 where the World object resides. The group parameter is, in fact, optional. We omitted it in the first Hello, World example because it was unnecessary when all of the slots are independent. So what happens if we mix calls to connect that use the group parameter and those that don't? The "unnamed" slots (i.e., those that have been connected without specifying a group name) can be placed at the front or back of the slot list (by passing boost::signals::at_front or boost::signals::at_back as the last parameter to connect, respectively), and defaults to the end of the list. When a group is specified, the final parameter describes where the slot will be placed within the group ordering. If we add a new slot to our example like this:
struct GoodMorning { void operator()() const { std::cout << "... and good morning!" << std::endl; } };

sig.connect(GoodMorning());
... we will get the result we wanted:
Hello, World! ... and good morning!
Passing values to and from slots
Slot Arguments (Beginner)
Signals can propagate arguments to each of the slots they call. For instance, a signal that propagates mouse motion events might want to pass along the new mouse coordinates and whether the mouse buttons are pressed.
As an example, we'll create a signal that passes two float arguments to its slots. Then we'll create a few slots that print the results of various arithmetic operations on these values.
void print_sum(float x, float y) { std::cout << "The sum is " << x+y << std::endl; }

void print_product(float x, float y) { std::cout << "The product is " << x*y << std::endl; }

void print_difference(float x, float y) { std::cout << "The difference is " << x-y << std::endl; }

void print_quotient(float x, float y) { std::cout << "The quotient is " << x/y << std::endl; }

Preferred syntax
Portable syntax
boost::signal
<void (float, float)> sig;

sig.connect(&print_sum); sig.connect(&print_product); sig.connect(&print_difference); sig.connect(&print_quotient);

sig(5, 3);
boost::signal2
<void, float, float> sig;

sig.connect(&print_sum); sig.connect(&print_product); sig.connect(&print_difference); sig.connect(&print_quotient);

sig(5, 3);

This program will print out the following:
The sum is 8 The difference is 2 The product is 15 The quotient is 1.66667
So any values that are given to sig when it is called like a function are passed to each of the slots. We have to declare the types of these values up front when we create the signal. The type boost::signal<void (float, float)> means that the signal has a void return value and takes two float values. Any slot connected to sig must therefore be able to take two float values.
Signal Return Values (Advanced)
Just as slots can receive arguments, they can also return values. These values can then be returned back to the caller of the signal through a combiner. The combiner is a mechanism that can take the results of calling slots (there many be no results or a hundred; we don't know until the program runs) and coalesces them into a single result to be returned to the caller. The single result is often a simple function of the results of the slot calls: the result of the last slot call, the maximum value returned by any slot, or a container of all of the results are some possibilities.
We can modify our previous arithmetic operations example slightly so that the slots all return the results of computing the product, quotient, sum, or difference. Then the signal itself can return a value based on these results to be printed:

Preferred syntax
Portable syntax
float product(float x, float y) { return x*y; } float quotient(float x, float y) { return x/y; } float sum(float x, float y) { return x+y; } float difference(float x, float y) { return x-y; }

boost::signal
<float (float x, float y)> sig;

sig.connect(&product); sig.connect(&quotient); sig.connect(&sum); sig.connect(&difference);

std::cout << sig(5, 3) << std::endl;
float product(float x, float y) { return x*y; } float quotient(float x, float y) { return x/y; } float sum(float x, float y) { return x+y; } float difference(float x, float y) { return x-y; }

boost::signal2
<float, float, float> sig;

sig.connect(&product); sig.connect(&quotient); sig.connect(&sum); sig.connect(&difference);

std::cout << sig(5, 3) << std::endl;

This example program will output 2. This is because the default behavior of a signal that has a return type (float, the first template argument given to the boost::signal class template) is to call all slots and then return the result returned by the last slot called. This behavior is admittedly silly for this example, because slots have no side effects and the result is the last slot connect.
A more interesting signal result would be the maximum of the values returned by any slot. To do this, we create a custom combiner that looks like this:
template<typename T> struct maximum { typedef T result_type;

template<typename InputIterator> T operator()(InputIterator first, InputIterator last) const { // If there are no slots to call, just return the // default-constructed value if (first == last) return T();

T max_value = *first++; while (first != last) { if (max_value < *first) max_value = *first; ++first; }

return max_value; } };
The maximum class template acts as a function object. Its result type is given by its template parameter, and this is the type it expects to be computing the maximum based on (e.g., maximum<float> would find the maximum float in a sequence of floats). When a maximum object is invoked, it is given an input iterator sequence [first, last) that includes the results of calling all of the slots. maximum uses this input iterator sequence to calculate the maximum element, and returns that maximum value.
We actually use this new function object type by installing it as a combiner for our signal. The combiner template argument follows the signal's calling signature:

Preferred syntax
Portable syntax
boost::signal
<float (float x, float y), maximum<float> > sig;
boost::signal2
<float, float, float, maximum<float> > sig;

Now we can connect slots that perform arithmetic functions and use the signal:
sig.connect(&quotient); sig.connect(&product); sig.connect(&sum); sig.connect(&difference);

std::cout << sig(5, 3) << std::endl;
The output of this program will be 15, because regardless of the order in which the slots are connected, the product of 5 and 3 will be larger than the quotient, sum, or difference.
In other cases we might want to return all of the values computed by the slots together, in one large data structure. This is easily done with a different combiner:
template<typename Container> struct aggregate_values { typedef Container result_type;

template<typename InputIterator> Container operator()(InputIterator first, InputIterator last) const { return Container(first, last); } };
Again, we can create a signal with this new combiner:

Preferred syntax
Portable syntax
boost::signal
<float (float, float), aggregate_values<std::vector<float> > > sig;

sig.connect(&quotient); sig.connect(&product); sig.connect(&sum); sig.connect(&difference);

std::vector<float> results = sig(5, 3); std::copy(results.begin(), results.end(), std::ostream_iterator<float>(cout, " "));
boost::signal2
<float, float, float, aggregate_values<std::vector<float> > > sig;

sig.connect(&quotient); sig.connect(&product); sig.connect(&sum); sig.connect(&difference);

std::vector<float> results = sig(5, 3); std::copy(results.begin(), results.end(), std::ostream_iterator<float>(cout, " "));

The output of this program will contain 15, 8, 1.6667, and 2. It is interesting here that the first template argument for the signal class, float, is not actually the return type of the signal. Instead, it is the return type used by the connected slots and will also be the value_type of the input iterators passed to the combiner. The combiner itself is a function object and its result_type member type becomes the return type of the signal.
The input iterators passed to the combiner transform dereference operations into slot calls. Combiners therefore have the option to invoke only some slots until some particular criterion is met. For instance, in a distributed computing system, the combiner may ask each remote system whether it will handle the request. Only one remote system needs to handle a particular request, so after a remote system accepts the work we do not want to ask any other remote systems to perform the same task. Such a combiner need only check the value returned when dereferencing the iterator, and return when the value is acceptable. The following combiner returns the first non-NULL pointer to a FulfilledRequest data structure, without asking any later slots to fulfill the request:
struct DistributeRequest { typedef FulfilledRequest* result_type;

template<typename InputIterator> result_type operator()(InputIterator first, InputIterator last) const { while (first != last) { if (result_type fulfilled = *first) return fulfilled; ++first; } return 0; } };
Connection Management
Disconnecting Slots (Beginner)
Slots aren't expected to exist indefinately after they are connected. Often slots are only used to receive a few events and are then disconnected, and the programmer needs control to decide when a slot should no longer be connected.
The entry point for managing connections explicitly is the boost::signals::connection class. The connection class uniquely represents the connection between a particular signal and a particular slot. The connected() method checks if the signal and slot are still connected, and the disconnect() method disconnects the signal and slot if they are connected before it is called. Each call to the signal's connect() method returns a connection object, which can be used to determine if the connection still exists or to disconnect the signal and slot.
boost::signals::connection c = sig.connect(HelloWorld()); if (c.connected()) { // c is still connected to the signal sig(); // Prints "Hello, World!" }

c.disconnect(); // Disconnect the HelloWorld object assert(!c.connected()); c isn't connected any more

sig(); // Does nothing: there are no connected slots
Scoped connections (Intermediate)
The boost::signals::scoped_connection class references a signal/slot connection that will be disconnected when the scoped_connection class goes out of scope. This ability is useful when a connection need only be temporary, e.g.,
{ boost::signals::scoped_connection c = sig.connect(ShortLived()); sig(); // will call ShortLived function object } sig(); // ShortLived function object no longer connected to sig
Disconnecting equivalent slots (Intermediate)
One can disconnect slots that are equivalent to a given function object using a form of the disconnect method, so long as the type of the function object has an accessible == operator. For instance:

Preferred syntax
Portable syntax
void foo(); void bar();

signal<void()> sig;

sig.connect(&foo); sig.connect(&bar);

// disconnects foo, but not bar sig.disconnect(&foo);
void foo(); void bar();

signal0<void> sig;

sig.connect(&foo); sig.connect(&bar);

// disconnects foo, but not bar sig.disconnect(&foo);

Automatic connection management (Intermediate)
Boost.Signals can automatically track the lifetime of objects involved in signal/slot connections, including automatic disconnection of slots when objects involved in the slot call are destroyed. For instance, consider a simple news delivery service, where clients connect to a news provider that then sends news to all connected clients as information arrives. The news delivery service may be constructed like this:

Preferred syntax
Portable syntax
class NewsItem { /* ... */ };

boost::signal<void (const NewsItem&)> deliverNews;
class NewsItem { /* ... */ };

boost::signal1<void, const NewsItem&> deliverNews;

Clients that wish to receive news updates need only connect a function object that can receive news items to the deliverNews signal. For instance, we may have a special message area in our application specifically for news, e.g.,:
struct NewsMessageArea : public MessageArea { public: // ...

void displayNews(const NewsItem& news) const { messageText = news.text(); update(); } };

// ... NewsMessageArea newsMessageArea = new NewsMessageArea(/* ... */); // ... deliverNews.connect(boost::bind(&NewsMessageArea::displayNews, newsMessageArea, _1));
However, what if the user closes the news message area, destroying the newsMessageArea object that deliverNews knows about? Most likely, a segmentation fault will occur. However, with Boost.Signals one need only make NewsMessageArea trackable, and the slot involving newsMessageArea will be disconnected when newsMessageArea is destroyed. The NewsMessageArea class is made trackable by deriving publicly from the boost::signals::trackable class, e.g.:
struct NewsMessageArea : public MessageArea, public boost::signals::trackable { // ... };
At this time there is a significant limitation to the use of trackable objects in making slot connections: function objects built using Boost.Bind are understood, such that pointers or references to trackable objects passed to boost::bind will be found and tracked.
Warning
: User-defined function objects and function objects from other libraries (e.g., Boost.Function or Boost.Lambda) do not implement the required interfaces for trackable object detection, and will silently ignore any bound trackable objects. Future versions of the Boost libraries will address this limitation.
When can disconnections occur? (Intermediate)
Signal/slot disconnections occur when any of these conditions occur:
•
The connection is explicitly disconnected via the connection's disconnect method directly, or indirectly via the signal's disconnect method or scoped_connection's destructor.
•
A trackable object bound to the slot is destroyed.
•
The signal is destroyed.
These events can occur at any time without disrupting a signal's calling sequence. If a signal/slot connection is disconnected at any time during a signal's calling sequence, the calling sequence will still continue but will not invoke the disconnected slot. Additionally, a signal may be destroyed while it is in a calling sequence, and which case it will complete its slot call sequence but may not be accessed directly.
Signals may be invoked recursively (e.g., a signal A calls a slot B that invokes signal A...). The disconnection behavior does not change in the recursive case, except that the slot calling sequence includes slot calls for all nested invocations of the signal.
Passing slots (Intermediate)
Slots in the Boost.Signals library are created from arbitrary function objects, and therefore have no fixed type. However, it is commonplace to require that slots be passed through interfaces that cannot be templates. Slots can be passed via the slot_type for each particular signal type and any function object compatible with the signature of the signal can be passed to a slot_type parameter. For instance:

Preferred syntax
Portable syntax
class Button { typedef boost::signal<void (int x, int y)> OnClick;

public: void doOnClick(const OnClick::slot_type& slot);

private: OnClick onClick; };

void Button::doOnClick( const OnClick::slot_type& slot ) { onClick.connect(slot); }

void printCoordinates(long x, long y) { std::cout << "(" << x << ", " << y << ")\n"; }

void f(Button& button) { button.doOnClick(&printCoordinates); }
class Button { typedef boost::signal2<void,int,int> OnClick;

public: void doOnClick(const OnClick::slot_type& slot);

private: OnClick onClick; };

void Button::doOnClick( const OnClick::slot_type& slot ) { onClick.connect(slot); }

void printCoordinates(long x, long y) { std::cout << "(" << x << ", " << y << ")\n"; }

void f(Button& button) { button.doOnClick(&printCoordinates); }

The doOnClick method is now functionally equivalent to the connect method of the onClick signal, but the details of the doOnClick method can be hidden in an implementation detail file.
Linking against the Signals library
Part of the Boost.Signals library is compiled into a binary library that must be linked into your application to use Signals. To build this library, execute the command bjam in either the top-level Boost directory or in libs/signals/build. On Unix, the directory libs/signals/build/bin-stage will then contain libraries named, e.g., libboost_signals.a that can be linked in your program with -lboost_signals.
On Windows, with Microsoft Visual C++ or Borland C++, the linking process is nearly automatic. As with the Regex library, the libraries in libs\signals\build\bin-stage will have mangled names and will be automatically be including in the link process. To link against the Signals library binary dynamically (e.g., using the Signals DLL), define BOOST_SIGNALS_DYN_LINK when building your application; to link statically, define BOOST_SIGNALS_STATIC_LINK.
Reference
Reference
Header <boost/signal.hpp>
namespace
boost { template<typename R, typename T1, typename T2, ..., typename TN, typename Combiner = last_value<R>, typename Group = int, typename GroupCompare = std::less<Group>, typename SlotFunction = functionN<R, T1, T2, ..., TN> > class signalN; template<typename Signature, typename Combiner = last_value<R>, typename Group = int, typename GroupCompare = std::less<Group>, typename SlotFunction = functionN<Signature> > class signal; namespace signals {

enum
connect_position { at_front, at_back }; } }
Class template signalN
Class template signalN -- Set of safe multicast callback types.
boost::signalN
template
<typename R, typename T1, typename T2, ..., typename TN, typename Combiner = last_value<R>, typename Group = int, typename GroupCompare = std::less<Group>, typename SlotFunction = functionN<R, T1, T2, ..., TN> > class signalN : public signals::trackable, private noncopyable // Exposition only { public: // types typedef typename Combiner::result_type result_type; typedef Combiner combiner_type; typedef Group group_type; typedef GroupCompare group_compare_type; typedef SlotFunction slot_function_type; typedef slot<SlotFunction> slot_type; typedef unspecified slot_result_type; typedef unspecified slot_call_iterator; typedef T1 argument_type; // If N == 1 typedef T1 first_argument_type; // If N == 2 typedef T2 second_argument_type; // If N == 2 typedef T1 arg1_type; typedef T2 arg2_type; . . . typedef TN argN_type;

// static constants
static
const
int
arity = N;

// construct/copy/destruct
signalN
(const combiner_type& = combiner_type(), const group_compare_type& = group_compare_type()); ~signalN();

// connection management
signals::connection
connect
(const slot_type&, signals::connect_position = signals::at_back); signals::connection connect(const group_type&, const slot_type&, signals::connect_position = signals::at_back); void disconnect(const group_type&); template<typename Slot> void disconnect(const Slot&); void disconnect_all_slots(); bool empty() const; std::size_t num_slots() const;

// invocation
result_type operator()(arg1_type, arg2_type, ..., argN_type); result_type operator()(arg1_type, arg2_type, ..., argN_type) const;

// combiner access
combiner_type& combiner(); const combiner_type& combiner() const; };
Description
Description
The class template signalN covers several related classes signal0, signal1, signal2, etc., where the number suffix describes the number of function parameters the signal and its connected slots will take. Instead of enumerating all classes, a single pattern signalN will be described, where N represents the number of function parameters.
signalN construct/copy/destruct
signalN
construct/copy/destruct
1.
signalN(const combiner_type& combiner = combiner_type(), const group_compare_type& compare = group_compare_type());
Effects
Initializes the signal to contain no slots, copies the given combiner into internal storage, and stores the given group comparison function object to compare groups.
Postconditions
this->empty()
2.
~signalN();
Effects
Disconnects all slots connected to *this.
signalN connection management
signalN
connection management
1.
signals::connection
connect(const slot_type& slot, signals::connect_position at = signals::at_back); signals::connection connect(const group_type& group, const slot_type& slot, signals::connect_position at = signals::at_back);
Effects
Connects the signal this to the incoming slot. If the slot is inactive, i.e., any of the trackable objects bound by the slot call have been destroyed, then the call to connect is a no-op. If the second version of connect is invoked, the slot is associated with the given group. The at parameter specifies where the slot should be connected: at_front indicates that the slot will be connected at the front of the list or group of slots and at_back indicates that the slot will be connected at the back of the list or group of slots.
Returns
A signals::connection object that references the newly-created connection between the signal and the slot; if the slot is inactive, returns a disconnected connection.
Throws
This routine meets the strong exception guarantee, where any exception thrown will cause the slot to not be connected to the signal.
Complexity
Constant time when connecting a slot without a group name or logarithmic in the number of groups when connecting to a particular group.
Notes
It is unspecified whether connecting a slot while the signal is calling will result in the slot being called immediately.
2.
void
disconnect(const group_type& group); template<typename Slot> void disconnect(const Slot& slot);
Effects
If the parameter is (convertible to) a group name, any slots in the given group are disconnected. Otherwise, any slots equal to the given slot are disconnected.
Throws
Will not throw unless a user destructor or equality operator == throws. If either throws, not all slots may be disconnected.
Complexity
If a group is given, O(lg g) + k where g is the number of groups in the signal and k is the number of slots in the group. Otherwise, linear in the number of slots connected to the signal.
3.
void
disconnect_all_slots();
Effects
Disconnects all slots connected to the signal.
Postconditions
this->empty()
.
Throws
If disconnecting a slot causes an exception to be thrown, not all slots may be disconnected.
Complexity
Linear in the number of slots known to the signal.
Notes
May be called at any time within the lifetime of the signal, including during calls to the signal's slots.
4.
bool
empty() const;
Returns
true
if no slots are connected to the signal, and false otherwise.
Throws
Will not throw.
Complexity
Linear in the number of slots known to the signal.
Rationale
Slots can disconnect at any point in time, including while those same slots are being invoked. It is therefore possible that the implementation must search through a list of disconnected slots to determine if any slots are still connected.
5.
std::size_t num_slots() const;
Returns
The number of slots connected to the signal
Throws
Will not throw.
Complexity
Linear in the number of slots known to the signal.
Rationale
Slots can disconnect at any point in time, including while those same slots are being invoked. It is therefore possible that the implementation must search through a list of disconnected slots to determine how many slots are still connected.
signalN invocation
signalN
invocation
1.
result_type operator()(arg1_type a1, arg2_type a2, ... , argN_type aN); result_type operator()(arg1_type a1, arg2_type a2, ... , argN_type aN) const;
Effects
Invokes the combiner with a slot_call_iterator range [first, last) corresponding to the sequence of calls to the slots connected to signal *this. Dereferencing an iterator in this range causes a slot call with the given set of parameters (a1, a2, ..., aN), the result of which is returned from the iterator dereference operation.
Returns
The result returned by the combiner.
Throws
If an exception is thrown by a slot call, or if the combiner does not dereference any slot past some given slot, all slots after that slot in the internal list of connected slots will not be invoked.
Notes
Only the slots associated with iterators that are actually dereferenced will be invoked. Multiple dereferences of the same iterator will not result in multiple slot invocations, because the return value of the slot will be cached.
The const version of the function call operator will invoke the combiner as const, whereas the non-const version will invoke the combiner as non-const.
Calling the function call operator may invoke undefined behavior if no slots are connected to the signal, depending on the combiner used. The default combiner is well-defined for zero slots when the return type is void but is undefined when the return type is any other type (because there is no way to synthesize a return value).
signalN combiner access
signalN
combiner access
1.
combiner_type& combiner(); const combiner_type& combiner() const;
Returns
A reference to the stored combiner.
Throws
Will not throw.
Class template signal
Class template signal -- Safe multicast callback.
boost::signal
template
<typename Signature, // Function type R (T1, T2, ..., TN) typename Combiner = last_value<R>, typename Group = int, typename GroupCompare = std::less<Group>, typename SlotFunction = functionN<Signature> > class signal : public signalN<R, T1, T2, ..., TN, Combiner, Group, GroupCompare, SlotFunction> { public: // construct/copy/destruct signal(const combiner_type& = combiner_type(), const group_compare_type& = group_compare_type()); };
Description
Description
Class template signal is a thin wrapper around the numbered class templates signal0, signal1, etc. It accepts a function type with N arguments instead of N separate arguments, and derives from the appropriate signalN instantiation.
All functionality of this class template is in its base class signalN.
signal construct/copy/destruct
signal
construct/copy/destruct
1.
signal(const combiner_type& combiner = combiner_type(), const group_compare_type& compare = group_compare_type());
Effects
Initializes the base class with the given combiner and comparison objects.
Header <boost/signals/slot.hpp>
namespace
boost { template<typename SlotFunction> class slot; }
Class template slot
Class template slot -- Pass slots as function arguments.
boost::slot
template
<typename SlotFunction> class slot { public: // construct/copy/destruct template<typename Slot> slot(Slot); };
Description
Description
slot construct/copy/destruct
slot
construct/copy/destruct
1.
template
<typename Slot> slot(Slot target);
Effects
Invokes visit_each (unqualified) to discover pointers and references to signals::trackable objects in target.
Initializes this to contain the incoming slot target, which may be any function object with which a SlotFunction can be constructed.
Header <boost/signals/trackable.hpp>
namespace
boost { namespace signals { class trackable; } }
Class trackable
Class trackable -- Enables safe use of multicast callbacks.
boost::signals::trackable
class
trackable { public: // construct/copy/destruct trackable(); trackable(const trackable&); trackable& operator=(const trackable&); ~trackable(); };
Description
Description
The trackable class provides automatic disconnection of signals and slots when objects bound in slots (via pointer or reference) are destroyed. The trackable class may only be used as a public base class for some other class; when used as such, that class may be bound to function objects used as part of slots. The manner in which a trackable object tracks the set of signal-slot connections it is a part of is unspecified.
The actual use of trackable is contingent on the presence of appropriate visit_each overloads for any type that may contain pointers or references to trackable objects.
trackable construct/copy/destruct
trackable
construct/copy/destruct
1.
trackable();
Effects
Sets the list of connected slots to empty.
Throws
Will not throw.
2.
trackable(const trackable& other);
Effects
Sets the list of connected slots to empty.
Throws
Will not throw.
Rationale
Signal-slot connections can only be created via calls to an explicit connect method, and therefore cannot be created here when trackable objects are copied.
3.
trackable& operator=(const trackable& other);
Effects
Sets the list of connected slots to empty.
Returns
*this
Throws
Will not throw.
Rationale
Signal-slot connections can only be created via calls to an explicit connect method, and therefore cannot be created here when trackable objects are copied.
4.
~trackable();
Effects
Disconnects all signal/slot connections that contain a pointer or reference to this trackable object that can be found by visit_each.
Header <boost/signals/connection.hpp>
namespace
boost { namespace signals { class connection; void swap(connection&, connection&); class scoped_connection; } }
Class connection
Class connection -- Query/disconnect a signal-slot connection.
boost::signals::connection
class
connection { public: // construct/copy/destruct connection(); connection(const connection&); connection& operator=(const connection&);

// connection management
void
disconnect
() const; bool connected() const;

// modifiers
void
swap
(const connection&);

// comparisons
bool
operator
==
(const connection&) const; bool operator<(const connection&) const; };

// specialized algorithms
void
swap
(connection&, connection&);
Description
Description
The connection class represents a connection between a Signal and a Slot. It is a lightweight object that has the ability to query whether the signal and slot are currently connected, and to disconnect the signal and slot. It is always safe to query or disconnect a connection.
connection construct/copy/destruct
connection
construct/copy/destruct
1.
connection();
Effects
Sets the currently represented connection to the NULL connection.
Postconditions
!this->connected()
.
Throws
Will not throw.
2.
connection(const connection& other);
Effects
this
references the connection referenced by other.
Throws
Will not throw.
3.
connection& operator=(const connection& other);
Effects
this
references the connection referenced by other.
Throws
Will not throw.
connection connection management
connection
connection management
1.
void
disconnect() const;
Effects
If this->connected(), disconnects the signal and slot referenced by this; otherwise, this operation is a no-op.
Postconditions
!this->connected()
.
2.
bool
connected() const;
Returns
true
if this references a non-NULL connection that is still active (connected), and false otherwise.
Throws
Will not throw.
connection modifiers
connection
modifiers
1.
void
swap(const connection& other);
Effects
Swaps the connections referenced in this and other.
Throws
Will not throw.
connection comparisons
connection
comparisons
1.
bool
operator
==(const connection& other) const;
Returns
true
if this and other reference the same connection or both reference the NULL connection, and false otherwise.
Throws
Will not throw.
2.
bool
operator
<(const connection& other) const;
Returns
true
if the connection referenced by this precedes the connection referenced by other based on some unspecified ordering, and false otherwise.
Throws
Will not throw.
connection specialized algorithms
connection
specialized algorithms
1.
void
swap(connection& x, connection& y);
Effects
x.swap(y)
Throws
Will not throw.
Class scoped_connection
Class scoped_connection -- Limits a signal-slot connection lifetime to a particular scope.
boost::signals::scoped_connection
class
scoped_connection : private noncopyable // Exposition only { public: // construct/copy/destruct scoped_connection(const connection&); ~scoped_connection();

// connection management
void
disconnect
() const; bool connected() const; };
Description
Description
scoped_connection construct/copy/destruct
scoped_connection
construct/copy/destruct
1.
scoped_connection(const connection& other);
Effects
this
references the connection referenced by other.
Throws
Will not throw.
2.
~scoped_connection();
Effects
If this->connected(), disconnects the signal-slot connection.
scoped_connection connection management
scoped_connection
connection management
1.
void
disconnect() const;
Effects
If this->connected(), disconnects the signal and slot referenced by this; otherwise, this operation is a no-op.
Postconditions
!this->connected()
.
2.
bool
connected() const;
Returns
true
if this references a non-NULL connection that is still active (connected), and false otherwise.
Throws
Will not throw.
Header <boost/visit_each.hpp>
namespace
boost { template<typename Visitor, typename T> void visit_each(const Visitor&, const T&, int); }
Function template visit_each
Function template visit_each -- Allow limited exploration of class members.
boost::visit_each
template
<typename Visitor, typename T> void visit_each(const Visitor& visitor, const T& t, int );
Description
Description
The visit_each mechanism allows a visitor to be applied to every subobject in a given object. It is used by the Signals library to discover signals::trackable objects within a function object, but other uses may surface if used universally (e.g., conservative garbage collection). To fit within the visit_each framework, a visit_each overload must be supplied for each object type.
Effects
visitor(t)
, and for every subobject x of t: •If x is a reference, visit_each(visitor, ref(x), 0)•Otherwise, visit_each(visitor, x, 0)
Notes
The third parameter is long for the fallback version of visit_each and the argument supplied to this third paramter must always be 0. The third parameter is an artifact of the widespread lack of proper function template ordering, and will be removed in the future.
Library authors will be expected to add additional overloads that specialize the T argument for their classes, so that subobjects can be visited.
Calls to visit_each are required to be unqualified, to enable argument-dependent lookup.
Header <boost/last_value.hpp>
namespace
boost { template<typename T> class last_value;

template
<> class last_value<void>; }
Class template last_value
Class template last_value -- Evaluate an InputIterator sequence and return the last value in the sequence.
boost::last_value
template
<typename T> class last_value { public: // types typedef T result_type;

// invocation
template
<typename InputIterator> result_type operator()(InputIterator, InputIterator) const; };
Description
Description
last_value invocation
last_value
invocation
1.
template
<typename InputIterator> result_type operator()(InputIterator first, InputIterator last) const;
Requires
first != last
Effects
Dereferences every iterator in the sequence [first, last).
Returns
The result of dereferencing the iterator last-1.
Specializations
Specializations
•
Class last_value<void>
Class last_value<void>
Class last_value<void> -- Evaluate an InputIterator sequence.
boost::last_value<void>
class
last_value<void> { public: // types typedef unspecified result_type;

// invocation
template
<typename InputIterator> result_type operator()(InputIterator, InputIterator) const; };
Description
Description
last_value invocation
last_value
invocation
1.
template
<typename InputIterator> result_type operator()(InputIterator first, InputIterator last) const;
Effects
Dereferences every iterator in the sequence [first, last).
Frequently Asked Questions
Frequently Asked Questions
1.
Don't noncopyable signal semantics mean that a class with a signal member will be noncopyable as well?
No. The compiler will not be able to generate a copy constructor or copy assignment operator for your class if it has a signal as a member, but you are free to write your own copy constructor and/or copy assignment operator. Just don't try to copy the signal.
2.
Is Boost.Signals thread-safe?
No. Using Boost.Signals in a multithreaded concept is very dangerous, and it is very likely that the results will be less than satisfying. Boost.Signals will support thread safety in the future.
3.
How do I get Boost.Signals to work with Qt?
When building with Qt, the Moc keywords signals and slots are defined using preprocessor macros, causing programs using Boost.Signals and Qt together to fail to compile. Although this is a problem with Qt and not Boost.Signals, a user can use the two systems together by defining the BOOST_SIGNALS_NAMESPACE macro to some other identifier (e.g., signalslib) when building and using the Boost.Signals library. Then the namespace of the Boost.Signals library will be boost::BOOST_SIGNALS_NAMESPACE instead of boost::signals. To retain the original namespace name in translation units that do not interact with Qt, you can use a namespace alias:
namespace boost { namespace signals = BOOST_SIGNALS_NAMESPACE; }
Design Overview
Design Overview
Type Erasure
"Type erasure", where static type information is eliminated by the use of dynamically dispatched interfaces, is used extensively within the Boost.Signals library to reduce the amount of code generated by template instantiation. Each signal must manage a list of slots and their associated connections, along with a std::map to map from group identifiers to their associated connections. However, instantiating this map for every token type, and perhaps within each translation unit (for some popular template instantiation strategies) increase compile time overhead and space overhead.
To combat this so-called "template bloat", we use Boost.Function and Boost.Any to store unknown types and operations. Then, all of the code for handling the list of slots and the mapping from slot identifiers to connections is factored into the class signal_base that deals exclusively with the any and function objects, hiding the actual implementations using the well-known pimpl idiom. The actual signalN class templates deal only with code that will change depending on the number of arguments or which is inherently template-dependent (such as connection).
connection
class
The connection class is central to the behavior of the Boost.Signals library. It is the only entity within the Boost.Signals system that has knowledge of all objects that are associated by a given connection. To be specific, the connection class itself is merely a thin wrapper over a shared_ptr to a basic_connection object.
connection
objects are stored by all participants in the Signals system: each trackable object contains a list of connection objects describing all connections it is a part of; similarly, all signals contain a set of pairs that define a slot. The pairs consist of a slot function object (generally a Boost.Function object) and a connection object (that will disconnect on destruction). Finally, the mapping from slot groups to slots is based on the key value in a std::multimap (the stored data in the std::multimap is the slot pair).
Slot Call Iterator
The slot call iterator is conceptually a stack of iterator adaptors that modify the behavior of the underlying iterator through the list of slots. The following table describes the type and behavior of each iterator adaptor required. Note that this is only a conceptual model: the implementation collapses all these layers into a single iterator adaptor because several popular compilers failed to compile the implementation of the conceptual model.

Iterator Adaptor
Purpose
Slot List Iterator
An iterator through the list of slots connected to a signal. The value_type of this iterator will be std::pair<any, connection>, where the any contains an instance of the slot function type.
Filter Iterator Adaptor
This filtering iterator adaptor filters out slots that have been disconnected, so we never see a disconnected slot in later stages.
Projection Iterator Adaptor
The projection iterator adaptor returns a reference to the first member of the pair that constitutes a connected slot (e.g., just the boost::any object that holds the slot function).
Transform Iterator Adaptor
This transform iterator adaptor performs an any_cast to extract a reference to the slot function with the appropriate slot function type.
Transform Iterator Adaptor
This transform iterator adaptor calls the function object returned by dereferencing the underlying iterator with the set of arguments given to the signal itself, and returns the result of that slot call.
Input Caching Iterator Adaptor
This iterator adaptor caches the result of dereferencing the underlying iterator. Therefore, dereferencing this iterator multiple times will only result in the underlying iterator being dereferenced once; thus, a slot can only be called once but its result can be used multiple times.
Slot Call Iterator
Iterates over calls to each slot.

visit_each
function template
The visit_each function template is a mechanism for discovering objects that are stored within another object. Function template visit_each takes three arguments: an object to explore, a visitor function object that is invoked with each subobject, and the int 0.
The third parameter is merely a temporary solution to the widespread lack of proper function template partial ordering. The primary visit_each function template specifies this third parameter type to be long, whereas any user specializations must specify their third parameter to be of type int. Thus, even though a broken compiler cannot tell the ordering between, e.g., a match against a parameter T and a parameter A<T>, it can determine that the conversion from the integer 0 to int is better than the conversion to long. The ordering determined by this conversion thus achieves partial ordering of the function templates in a limited, but successful, way. The following example illustrates the use of this technique:
template<typename> class A {}; template<typename T> void foo(T, long); template<typename T> void foo(A<T>, int); A<T> at; foo(at, 0);
In this example, we assume that our compiler can not tell that A<T> is a better match than T, and therefore assume that the function templates cannot be ordered based on that parameter. Then the conversion from 0 to int is better than the conversion from 0 to long, and the second function template is chosen.
Design Rationale
Design Rationale
Choice of Slot Definitions
The definition of a slot differs amongst signals and slots libraries. Within Boost.Signals, a slot is defined in a very loose manner: it can be any function object that is callable given parameters of the types specified by the signal, and whose return value is convertible to the result type expected by the signal. However, alternative definitions have associated pros and cons that were considered prior to the construction of Boost.Signals.
•
Slots derive from a specific base class
: generally a scheme such as this will require all user-defined slots to derive from some library-specified Slot abstract class that defines a virtual function calling the slot. Adaptors can be used to convert a definition such as this to a definition similar to that used by Boost.Signals, but the use of a large number of small adaptor classes containing virtual functions has been found to cause an unacceptable increase in the size of executables (polymorphic class types require more code than non-polymorphic types).
This approach does have the benefit of simplicity of implementation and user interface, from an object-oriented perspective.
•
Slots constructed from a set of primitives
: in this scheme the slot can have a limited set of types (often derived from a common abstract base class) that are constructed from some library-defined set of primitives that often include conversions from free function pointers and member function pointers, and a limited set of binding capabilities. Such an approach is reasonably simple and cover most common cases, but it does not allow a large degree of flexibility in slot construction. Libraries for function object composition have become quite advanced and it is out of the scope of a signals and slots library to encorporate such enhancements. Thus Boost.Signals does not include argument binding or function object composition primitives, but instead provides a hook (via the visit_each mechanism) that allows existing binder/composition libraries to provide the necessary information to Signals.
Users not satisfied with the slot definition choice may opt to replace the default slot function type with an alternative that meets their specific needs.
User-level Connection Management
Users need to have fine control over the connection of signals to slots and their eventual disconnection. The approach taken by Boost.Signals is to return a connection object that enables connected/disconnected query, manual disconnection, and an automatic disconnection on destruction mode. Some other possible interfaces include:
•
Pass slot to disconnect
: in this interface model, the disconnection of a slot connected with sig.connect(slot) is performed via sig.disconnect(slot). Internally, a linear search using slot comparison is performed and the slot, if found, is removed from the list. Unfortunately, querying connectedness will generally also end up as linear-time operations. This model also fails for implementation reasons when slots become more complex than simple function pointers, member function pointers and a limited set of compositions and argument binders: to match the slot given in the call to disconnect with an existing slot we would need to be able to compare arbitrary function objects, which is not feasible.
•
Pass a token to disconnect
: this approach identifies slots with a token that is easily comparable (e.g., a string), enabling slots to be arbitrary function objects. While this approach is essentially equivalent to the approach taken by Boost.Signals, it is possibly more error-prone for several reasons:
•
Connections and disconnections must be paired, so the problem becomes similar to the problems incurred when pairing new and delete for dynamic memory allocation. While errors of this sort would not be catastrophic for a signals and slots implementation, their detection is generally nontrivial.
•
Tokens must be unique, otherwise two slots will have the same name and will be indistinguishable. In environments where many connections will be made dynamically, name generation becomes an additional task for the user. Uniqueness of tokens also results in an additional failure mode when attempting to connect a slot using a token that has already been used.
•
More parameterization would be required, because the token type must be user-defined. Additional parameterization steepens the learning curver and overcomplicates a simple interface.
This type of interface is supported in Boost.Signals via the slot grouping mechanism. It augments the connection object-based connection management scheme.
Combiner Interface
The Combiner interface was chosen to mimic a call to an algorithm in the C++ standard library. It is felt that by viewing slot call results as merely a sequence of values accessed by input iterators, the combiner interface would be most natural to a proficient C++ programmer. Competing interface design generally required the combiners to be constructed to conform to an interface that would be customized for (and limited to) the Signals library. While these interfaces are generally enable more straighforward implementation of the signals & slots libraries, the combiners are unfortunately not reusable (either in other signals & slots libraries or within other generic algorithms), and the learning curve is steepened slightly to learn the specific combiner interface.
The Signals formulation of combiners is based on the combiner using the "pull" mode of communication, instead of the more complex "push" mechanism. With a "pull" mechanism, the combiner's state can be kept on the stack and in the program counter, because whenever new data is required (i.e., calling the next slot to retrieve its return value), there is a simple interface to retrieve that data immediately and without returning from the combiner's code. Contrast this with the "push" mechanism, where the combiner must keep all state in class members because the combiner's routines will be invoked for each signal called. Compare, for example, a combiner that returns the maximum element from calling the slots. If the maximum element ever exceeds 100, no more slots are to be called.

Pull
Push
struct pull_max { typedef int result_type;

template<typename InputIterator> result_type operator()(InputIterator first, InputIterator last) { if (first == last) throw std::runtime_error("Empty!");

int max_value = *first++; while(first != last && *first <= 100) { if (*first > max_value) max_value = *first; ++first; }

return max_value; } };
struct push_max { typedef int result_type;

push_max() : max_value(), got_first(false) {}

// returns false when we want to stop bool operator()(int result) { if (result > 100) return false;

if (!got_first) { got_first = true; max_value = result; return true; }

if (result > max_value) max_value = result;

return true; }

int get_value() const { if (!got_first) throw std::runtime_error("Empty!"); return max_value; }

private: int max_value; bool got_first; };

There are several points to note in these examples. The "pull" version is a reusable function object that is based on an input iterator sequence with an integer value_type, and is very straightforward in design. The "push" model, on the other hand, relies on an interface specific to the caller and is not generally reusable. It also requires extra state values to determine, for instance, if any elements have been received. Though code quality and ease-of-use is generally subjective, the "pull" model is clearly shorter and more reusable and will often be construed as easier to write and understand, even outside the context of a signals & slots library.
The cost of the "pull" combiner interface is paid in the implementation of the Signals library itself. To correctly handle slot disconnections during calls (e.g., when the dereference operator is invoked), one must construct the iterator to skip over disconnected slots. Additionally, the iterator must carry with it the set of arguments to pass to each slot (although a reference to a structure containing those arguments suffices), and must cache the result of calling the slot so that multiple dereferences don't result in multiple calls. This apparently requires a large degree of overhead, though if one considers the entire process of invoking slots one sees that the overhead is nearly equivalent to that in the "push" model, but we have inverted the control structures to make iteration and dereference complex (instead of making combiner state-finding complex).
Connection Interfaces: += operator
Boost.Signals supports a connection syntax with the form sig.connect(slot), but a more terse syntax sig += slot has been suggested (and has been used by other signals & slots implementations). There are several reasons as to why this syntax has been rejected:
•
It's unnecessary
: the connection syntax supplied by Boost.Signals is no less powerful that that supplied by the += operator. The savings in typing (connect() vs. +=) is essentially negligible. Furthermore, one could argue that calling connect() is more readable than an overload of +=.
•
Ambiguous return type
: there is an ambiguity concerning the return value of the += operation: should it be a reference to the signal itself, to enable sig += slot1 += slot2, or should it return a connection for the newly-created signal/slot connection?
•
Gateway to operators -=, +
: when one has added a connection operator +=, it seems natural to have a disconnection operator -=. However, this presents problems when the library allows arbitrary function objects to implicitly become slots, because slots are no longer comparable.
The second obvious addition when one has operator+= would be to add a + operator that supports addition of multiple slots, followed by assignment to a signal. However, this would require implementing + such that it can accept any two function objects, which is technically infeasible.
trackable
rationale
The trackable class is the primary user interface to automatic connection lifetime management, and its design affects users directly. Two issues stick out most: the odd copying behavior of trackable, and the limitation requiring users to derive from trackable to create types that can participate in automatic connection management.
trackable
copying behavior
The copying behavior of trackable is essentially that trackable subobjects are never copied; instead, the copy operation is merely a no-op. To understand this, we look at the nature of a signal-slot connection and note that the connection is based on the entities that are being connected; when one of the entities is destroyed, the connection is destroyed. Therefore, when a trackable subobject is copied, we cannot copy the connections because the connections don't refer to the target entity - they refer to the source entity. This reason is dual to the reason signals are noncopyable: the slots connected to them are connected to that particular signal, not the data contained in the signal.
Why derivation from trackable?
For trackable to work properly, there are two constraints:
•
trackable
must have storage space to keep track of all connections made to this object.
•
trackable
must be notified when the object is being destructed so that it can disconnect its connections.
Clearly, deriving from trackable meets these two guidelines. We have not yet found a superior solution.
Comparison with other Signal/Slot implementations
libsigc++
libsigc++
is a C++ signals & slots library that originally started as part of an initiative to wrap the C interfaces to GTK libraries in C++, and has grown to be a separate library maintained by Karl Nelson. There are many similarities between libsigc++ and Boost.Signals, and indeed Boost.Signals was strongly influenced by Karl Nelson and libsigc++. A cursory inspection of each library will find a similar syntax for the construction of signals and in the use of connections and automatic connection lifetime management. There are some major differences in design that separate these libraries:
•
Slot definitions
: slots in libsigc++ are created using a set of primitives defined by the library. These primitives allow binding of objects (as part of the library), explicit adaptation from the argument and return types of the signal to the argument and return types of the slot (libsigc++ is, by default, more strict about types than Boost.Signals). A discussion of this approach with a comparison against the approach taken by Boost.Signals is given in Choice of Slot Definitions.
•
Combiner/Marshaller interface
: the equivalent to Boost.Signals combiners in libsigc++ are the marshallers. Marshallers are similar to the "push" interface described in Combiner Interface, and a proper treatment of the topic is given there.
.NET delegates
Microsoft
has introduced the .NET Framework and an associated set of languages and language extensions, one of which is the delegate. Delegates are similar to signals and slots, but they are more limited than most C++ signals and slots implementations in that they:
•
Require exact type matches between a delegate and what it is calling.
•
Only return the result of the last target called, with no option for customization.
•
Must call a method with this already bound.
Testsuite
Testsuite
Acceptance tests

Test
Type
Description
If failing...
dead_slot_test.cpp
run
Ensure that calling connect with a slot that has already been disconnected via deletion does not actually connect to the slot.
deletion_test.cpp
run
Test deletion of slots.
ordering_test.cpp
run
Test slot group ordering.
signal_n_test.cpp
run
Basic test of signal/slot connections and invocation using the boost::signalN class templates.
signal_test.cpp
run
Basic test of signal/slot connections and invocation using the boost::signal class template.
The boost::signal class template may not be usable on your compiler. However, the boost::signalN class templates may still be usable.
trackable_test.cpp
run
Test automatic lifetime management using boost::trackable objects.

Boost String Algorithms Library

Boost String Algorithms Library

Boost String Algorithms Library
Pavol Droba
Copyright © 2002-2004 Pavol Droba
Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
The String Algorithm Library provides a generic implementation of string-related algorithms which are missing in STL. It is an extension to the algorithms library of STL and it includes trimming, case conversion, predicates and find/replace functions. All of them come in different variants so it is easier to choose the best fit for a particular need.
The implementation is not restricted to work with a particular container (like std::basic_string), rather it is as generic as possible. This generalization is not compromising the performance since algorithms are using container specific features when it means a performance gain.
Important note: In this documentation we use term string to designate a sequence of characters stored in an arbitrary container. A string is not restricted to std::basic_string and character does not have to be char or wchar_t, although these are most common candidates.
Consult the design chapter to see precise specification of supported string types.
The library interface functions and classes are defined in namespace boost::algorithm, and they are lifted into namespace boost via using declaration.
The documentation is divided into several sections. For a quick start read the Usage section followed by Quick Reference. The Design Topics, Concepts and Rationale provide some explanation about the library design and structure an explain how it should be used. See the Reference for the complete list of provided utilities and algorithms. Functions and classes in the reference are organized by the headers in which they are defined. The reference contains links to the detailed description for every entity in the library.
Usage
Usage
First Example
Using the algorithms is straightforward. Let us have a look at the first example:
#include <boost/algorithm/string.hpp> using namespace std; using namespace boost;

// ...

string str1(" hello world! "); to_upper(str1); // str1 == " HELLO WORLD! " trim(str1); // str1 == "HELLO WORLD!"

string str2= to_lower_copy( ireplace_first_copy( str1,"hello","goodbye")); // str2 == "goodbye world!"
This example converts str1 to upper case and trims spaces from the start and the end of the string. str2 is then created as a copy of str1 with "hello" replaced with "goodbye". This example demonstrates several important concepts used in the library:
•
Container parameters:
Unlike in the STL algorithms, parameters are not specified only in the form of iterators. The STL convention allows for great flexibility, but it has several limitations. It is not possible to stack algorithms together, because a container is passed in two parameters. Therefore it is not possible to use a return value from another algorithm. It is considerably easier to write to_lower(str1), than to_lower(str1.begin(), str1.end()).
The magic of collection_traits provides a uniform way of handling different string types. If there is a need to pass a pair of iterators, iterator_range can be used to package iterators into a structure with a compatible interface.
•
Copy vs. Mutable:
Many algorithms in the library are performing a transformation of the input. The transformation can be done in-place, mutating the input sequence, or a copy of the transformed input can be created, leaving the input intact. None of these possibilities is superior to the other one and both have different advantages and disadvantages. For this reason, both are provided with the library.
•
Algorithm stacking:
Copy versions return a transformed input as a result, thus allow a simple chaining of transformations within one expression (i.e. one can write trim_copy(to_upper_copy(s))). Mutable versions have void return, to avoid misuse.
•
Naming:
Naming follows the conventions from the Standard C++ Library. If there is a copy and a mutable version of the same algorithm, the mutable version has no suffix and the copy version has the suffix _copy. Some algorithms have the prefix i (e.g. ifind_first()). This prefix identifies that the algorithm works in a case-insensitive manner.
To use the library, include the boost/algorithm/string.hpp header. If the regex related functions are needed, include the boost/algorithm/string_regex.hpp header.
Case conversion
STL has a nice way of converting character case. Unfortunately, it works only for a single character and we want to convert a string,
string str1("HeLlO WoRld!"); to_upper(str1); // str1=="HELLO WORLD!"
to_upper()
and to_lower() convert the case of characters in a string using a specified locale.
For more information see the reference for boost/algorithm/string/case_conv.hpp.
Predicates and Classification
A part of the library deals with string related predicates. Consider this example:
bool is_executable( string& filename ) { return iends_with(filename, ".exe") || iends_with(filename, ".com"); }

// ... string str1("command.com"); cout << str1 << is_executable("command.com")? "is": "is not" << "an executable" << endl; // prints "command.com is an executable"

//.. char text1[]="hello world!"; cout << text1 << all( text1, is_lower() )? "is": "is not" << " written in the lower case" << endl; // prints "hello world! is written in the lower case"
The predicates determine whether if a substring is contained in the input string under various conditions. The conditions are: a string starts with the substring, ends with the substring, simply contains the substring or if both strings are equal. See the reference for boost/algorithm/string/predicate.hpp for more details.
In addition the algorithm all() checks all elements of a container to satisfy a condition specified by a predicate. This predicate can be any unary predicate, but the library provides a bunch of useful string-related predicates and combinators ready for use. These are located in the boost/algorithm/string/classification.hpp header. Classification predicates can be combined using logical combinators to form a more complex expressions. For example: is_from_range('a','z') || is_digit()
Trimming
When parsing the input from a user, strings usually have unwanted leading or trailing characters. To get rid of them, we need trim functions:
string str1=" hello world! "; string str2=trim_left_copy(str1); // str2 == "hello world! " string str3=trim_right_copy(str2); // str3 == " hello world!" trim(str1); // str1 == "hello world!"

string phone="00423333444"; // remove leading 0 from the phone number trim_left_if(phone,is_any_of("0")); // phone == "423333444"
It is possible to trim the spaces on the right, on the left or on both sides of a string. And for those cases when there is a need to remove something else than blank space, there are _if variants. Using these, a user can specify a functor which will select the space to be removed. It is possible to use classification predicates like is_digit() mentioned in the previous paragraph. See the reference for the boost/algorithm/string/trim.hpp.
Find algorithms
The library contains a set of find algorithms. Here is an example:
char text[]="hello dolly!"; iterator_range<char*> result=find_last(text,"ll");

transform( result.begin(), result.end(), result.begin(), bind2nd(plus<char>(), 1) ); // text = "hello dommy!"

to_upper(result); // text == "hello doMMy!"

// iterator_range is convertible to bool if(find_first(text, "dolly")) { cout << "Dolly is there" << endl; }
We have used find_last() to search the text for "ll". The result is given in the iterator_range. This range delimits the part of the input which satisfies the find criteria. In our example it is the last occurrence of "ll".

As we can see, input of the find_last() algorithm can be also char[] because this type is supported by collection_traits.

The following lines transform the result. Notice that iterator_range has familiar begin() and end() methods, so it can be used like any other STL container. Also it is convertible to bool therefore it is easy to use find algorithms for a simple containment checking.
Find algorithms are located in boost/algorithm/string/find.hpp.
Replace Algorithms
Find algorithms can be used for searching for a specific part of string. Replace goes one step further. After a matching part is found, it is substituted with something else. The substitution is computed from the original, using some transformation.
string str1="Hello Dolly, Hello World!" replace_first(str1, "Dolly", "Jane"); // str1 == "Hello Jane, Hello World!" replace_last(str1, "Hello", "Goodbye"); // str1 == "Hello Jane, Goodbye World!" erase_all(str1, " "); // str1 == "HelloJane,GoodbyeWorld!" erase_head(str1, 6); // str1 == "Jane,GoodbyeWorld!"
For the complete list of replace and erase functions see the reference. There is a lot of predefined function for common usage, however, the library allows you to define a custom replace() that suits a specific need. There is a generic find_format() function which takes two parameters. The first one is a Finder object, the second one is a Formatter object. The Finder object is a functor which performs the searching for the replacement part. The Formatter object takes the result of the Finder (usually a reference to the found substring) and creates a substitute for it. Replace algorithm puts these two together and makes the desired substitution.
Check boost/algorithm/string/replace.hpp, boost/algorithm/string/erase.hpp and boost/algorithm/string/find_format.hpp for reference.
Find Iterator
An extension to find algorithms it the Find Iterator. Instead of searching for just a one part of a string, the find iterator allows us to iterate over the substrings matching the specified criteria. This facility is using the Finder to incrementally search the string. Dereferencing a find iterator yields an iterator_range object, that delimits the current match.
There are two iterators provided find_iterator and split_iterator. The former iterates over substrings that are found using the specified Finder. The latter iterates over the gaps between these substrings.
string str1("abc-*-ABC-*-aBc"); // Find all 'abc' substrings (ignoring the case) // Create a find_iterator typedef find_iterator<string::iterator> string_find_iterator; for(string_find_iterator It= make_find_iterator(str1, first_finder("abc", is_iequal())); It!=string_find_iterator(); ++It) { cout << copy_iterator_range<std::string>(*It) << endl; }

// Output will be: // abc // ABC // aBC

typedef split_iterator<string::iterator> string_split_iterator; for(string_find_iterator It= make_split_iterator(str1, first_finder("-*-", is_iequal())); It!=string_find_iterator(); ++It) { cout << copy_iterator_range<std::string>(*It) << endl; }

// Output will be: // abc // ABC // aBC
Note that the find iterators have only one template parameter. It is the base iterator type. The Finder is specified at runtime. This allows us to typedef a find iterator for common string types and reuse it. Additionally make_*_iterator functions help to construct a find iterator for a particular collection.
See the reference in boost/algorithm/string/find_iterator.hpp.
Split
Split algorithms are an extension to the find iterator for one common usage scenario. These algorithms use a find iterator and store all matches into the provided container. This container must be able to hold copies (e.g. std::string) or references (e.g. iterator_range) of the extracted substrings.
Two algorithms are provided. find_all() finds all copies of a string in the input. split() splits the input into parts.
string str1("hello abc-*-ABC-*-aBc goodbye");

typedef vector< iterator_range<string::iterator> > find_vector_type;

find_vector_type FindVec; // #1: Search for separators ifind_all( FindVec, str1, "abc" ); // FindVec == { [abc],[ABC],[aBc] }

typedef vector< string > split_vector_type;

split_vector_type SplitVec; // #2: Search for tokens split( SplitVec, str1, is_any_of("-*") ); // SplitVec == { "hello abc","ABC","aBc goodbye" }
[hello]
designates an iterator_range delimiting this substring.
First example show how to construct a container to hold references to all extracted substrings. Algorithm ifind_all() puts into FindVec references to all substrings that are in case-insensitive manner equal to "abc".
Second example uses split() to split string str1 into parts separated by characters '-' or '*'. These parts are then put into the SplitVec. It is possible to specify if adjacent separators are concatenated or not.
More information can be found in the reference: boost/algorithm/string/split.hpp.
Quick Reference
Quick Reference
Algorithms
Table 1. Case Conversion

Algorithm name
Description
Functions
to_upper
Convert a string to upper case
to_upper_copy()
to_upper()
to_lower
Convert a string to lower case
to_lower_copy()
to_lower()

Table 2. Trimming

Algorithm name
Description
Functions
trim_left
Remove leading spaces from a string
trim_left_copy_if()
trim_left_if()
trim_left_copy()
trim_left()
trim_right
Remove trailing spaces from a string
trim_right_copy_if()
trim_right_if()
trim_right_copy()
trim_right()
trim
Remove leading and trailing spaces from a string
trim_copy_if()
trim_if()
trim_copy()
trim()

Table 3. Predicates

Algorithm name
Description
Functions
starts_with
Check if a string is a prefix of the other one
starts_with()
istarts_with()
ends_with
Check if a string is a suffix of the other one
ends_with()
iends_with()
contains
Check if a string is contained of the other one
contains()
icontains()
equals
Check if two strings are equal
equals()
iequals()
all
Check if all elements of a string satisfy the given predicate
all()

Table 4. Find algorithms

Algorithm name
Description
Functions
find_first
Find the first occurrence of a string in the input
find_first()
ifind_first()
find_last
Find the last occurrence of a string in the input
find_last()
ifind_last()
find_nth
Find the nth (zero-indexed) occurrence of a string in the input
find_nth()
ifind_nth()
find_head
Retrieve the head of a string
find_head()
find_tail
Retrieve the tail of a string
find_tail()
find_token
Find first matching token in the string
find_token()
find_regex
Use the regular expression to search the string
find_regex()
find
Generic find algorithm
find()

Table 5. Erase/Replace

Algorithm name
Description
Functions
replace/erase_first
Replace/Erase the first occurrence of a string in the input
replace_first()
replace_first_copy()
ireplace_first()
ireplace_first_copy()
erase_first()
erase_first_copy()
ierase_first()
ierase_first_copy()
replace/erase_last
Replace/Erase the last occurrence of a string in the input
replace_last()
replace_last_copy()
ireplace_last()
ireplace_last_copy()
erase_last()
erase_last_copy()
ierase_last()
ierase_last_copy()
replace/erase_nth
Replace/Erase the nth (zero-indexed) occurrence of a string in the input
replace_nth()
replace_nth_copy()
ireplace_nth()
ireplace_nth_copy()
erase_nth()
erase_nth_copy()
ierase_nth()
ierase_nth_copy()
replace/erase_all
Replace/Erase the all occurrences of a string in the input
replace_all()
replace_all_copy()
ireplace_all()
ireplace_all_copy()
erase_all()
erase_all_copy()
ierase_all()
ierase_all_copy()
replace/erase_head
Replace/Erase the head of the input
replace_head()
replace_head_copy()
erase_head()
erase_head_copy()
replace/erase_tail
Replace/Erase the tail of the input
replace_tail()
replace_tail_copy()
erase_tail()
erase_tail_copy()
replace/erase_regex
Replace/Erase a substring matching the given regular expression
replace_regex()
replace_regex_copy()
erase_regex()
erase_regex_copy()
replace/erase_regex_all
Replace/Erase all substrings matching the given regular expression
replace_all_regex()
replace_all_regex_copy()
erase_all_regex()
erase_all_regex_copy()
find_format
Generic replace algorithm
find_format()
find_format_copy()
find_format_all()
find_format_all_copy()()

Table 6. Split

Algorithm name
Description
Functions
find_all
Find/Extract all matching substrings in the input
find_all()
ifind_all()
find_all_regex()
split
Split input into parts
split()
split_regex()

Finders and Formatters
Table 7. Finders

Finder
Description
Generators
first_finder
Search for the first match of the string in an input
first_finder()
last_finder
Search for the last match of the string in an input
last_finder()
nth_finder
Search for the nth (zero-indexed) match of the string in an input
nth_finder()
head_finder
Retrieve the head of an input
head_finder()
tail_finder
Retrieve the tail of an input
tail_finder()
token_finder
Search for a matching token in an input
token_finder()
range_finder
Do no search, always returns the given range
range_finder()
regex_finder
Search for a substring matching the given regex
regex_finder()

Table 8. Formatters

Formatter
Description
Generators
const_formatter
Constant formatter. Always return the specified string
const_formatter()
identity_formatter
Identity formatter. Return unmodified input input
identity_formatter()
empty_formatter
Null formatter. Always return an empty string
empty_formatter()
regex_formatter
Regex formatter. Format regex match using the specification in the format string
regex_formatter()

Iterators
Table 9. Find Iterators

Iterator name
Description
Iterator class
find_iterator
Iterates through matching substrings in the input
find_iterator
split_iterator
Iterates through gaps between matching substrings in the input
split_iterator

Classification
Table 10. Predicates

Predicate name
Description
Generator
is_classified
Generic ctype mask based classification
is_classified()
is_space
Recognize spaces
is_space()
is_alnum
Recognize alphanumeric characters
is_alnum()
is_alpha
Recognize letters
is_alpha()
is_cntrl
Recognize control characters
is_cntrl()
is_digit
Recognize decimal digits
is_digit()
is_graph
Recognize graphical characters
is_graph()
is_lower
Recognize lower case characters
is_lower()
is_print
Recognize printable characters
is_print()
is_punct
Recognize punctuation characters
is_punct()
is_upper
Recognize uppercase characters
is_upper()
is_xdigit
Recognize hexadecimal digits
is_xdigit()

Design Topics
Design Topics
String Representation
As the name suggest, this library works mainly with strings. However, in the context of this library, a string is not restricted to any particular implementation (like std::basic_string), rather it is a concept. This allows the algorithms in this library to be reused for any string type, that satisfies the given requirements.
Definition:
A string is a collection of characters accessible in sequential ordered fashion. Character is any value type with "cheap" copying and assignment.
First requirement of string-type is that it must accessible using collection traits. This facility allows to access the elements inside the string in a uniform iterator-based fashion. This requirement is actually less stringent than that of collection concept. It implements an external collection interface. This is sufficient for our library
Second requirement defines the way in which the characters are stored in the string. Algorithms in this library work with an assumption that copying a character is cheaper then allocating extra storage to cache results. This is a natural assumption for common character types. Algorithms will work even if this requirement is not satisfied, however at the cost of performance degradation. In addition some algorithms have additional requirements on the string-type. Particularly, it is required that an algorithm can create a new string of the given type. In this case, it is required that the type satisfies the sequence (Std §23.1.1) requirements.
In the reference and also in the code, requirement on the string type is designated by the name of template argument. CollectionT means that the basic collection requirements must hold. SequenceT designates extended sequence requirements.
iterator_range
class
An iterator_range is an encapsulation of a pair of iterators that delimit a sequence (or, a range). This concept is widely used by sequence manipulating algorithms. Although being so useful, there no direct support for it in the standard library (The closest thing is that some algorithms return a pair of iterators). Instead all STL algorithms have two distinct parameters for beginning and end of a range. This design is natural for implementation of generic algorithms, but it forbids to work with a range as a single value.
It is possible to encapsulate a range in std::pair<>, but std::pair<> is an overly generic encapsulation, so it is not best match for a range. For instance, it does not enforce that begin and end iterators be of the same type.
Naturally the range concept is heavily used also in this library. During the development of the library, it was discovered, that there is a need for a reasonable encapsulation for it, since core part of the library deals with substring searching algorithms and any such algorithm returns a range delimiting the result of the search. std::pair<> was deemed as unsuitable. Therefore the iterator_range was defined.
The intention of the iterator_range class is to manage a range as a single value and provide a basic interface for common operations. Its interface is similar to that of a collection. In addition to begin() and end() accessors, it has member functions for checking whether the range is empty, or to determine the size of the range. It also has a set of member typedefs that extract type information from the encapsulated iterators. As such, the interface is compatible with the collection traits requirements so it is possible to use this class as a parameter to many algorithms in this library.
iterator_range
will be moved to Boost.Range library in the future releases. The internal version will be deprecated then.
Collection Traits
Collection traits provide uniform access to different types of collections . This functionality allows to write generic algorithms which work with several different kinds of collections. For this library it means, that, for instance, many algorithms work with std::string as well as with char[]. This facility implements the external collection concept.
The following collection types are supported: • Standard containers • Built-in arrays (like int[]) • Null terminated strings (this includes char[],wchar_t[],char*, and wchar_t*) • std::pair<iterator,iterator>
Collection traits support a subset of the container concept (Std §23.1). This subset can be described as an input container concept, e.g. a container with immutable content. Its definition can be found in the header boost/algorithm/string/collection_traits.hpp.
In the table C denotes a container and c is an object of C.
Table 11. Collection Traits

Name
Standard collection equivalent
Description
value_type_of<C>
::type
C::value_type
Type of contained values
difference_type_of<C>
::type
C::difference_type
difference type of the collection
iterator_of<C>
::type
C::iterator
iterator type of the collection
const_iterator_of<C>
::type
C::const_iterator
const_iterator type of the collection
result_iterator_of<C>
::type
result_iterator type of the collection. This type maps to C::iterator for mutable collection and C::const_iterator for const collection.
begin(c)
c.begin()
Gets the iterator pointing to the start of the collection.
end(c)
c.end()
Gets the iterator pointing to the end of the collection.
size(c)
c.size()
Gets the size of the collection.
empty(c)
c.empty()
Checks if the collection is empty.

The collection traits are only a temporary part of this library. They will be replaced in the future releases by Boost.Range library. Use of the internal implementation will be deprecated then.
Sequence Traits
The major difference between std::list and std::vector is not in the interfaces they provide, but rather in the inner details of the class and the way how it performs various operations. The problem is that it is not possible to infer this difference from the definitions of classes without some special mechanism. However, some algorithms can run significantly faster with the knowledge of the properties of a particular container.
Sequence traits allow one to specify additional properties of a sequence container (see Std.§32.2). These properties are then used by algorithms to select optimized handling for some operations. The sequence traits are declared in the header boost/algorithm/string/sequence_traits.hpp.
In the table C denotes a container and c is an object of C.
Table 12. Sequence Traits

Trait
Description
has_native_replace<C>
::value
Specifies that the sequence has std::string like replace method
has_stable_iterators<C>
::value
Specifies that the sequence has stable iterators. It means, that operations like insert/erase/replace do not invalidate iterators.
has_const_time_insert<C>
::value
Specifies that the insert method of the sequence has constant time complexity.
has_const_time_erase<C>
::value
Specifies that the erase method of the sequence has constant time complexity

Current implementation contains specializations for std::list<T> and std::basic_string<T> from the standard library and SGI's std::rope<T> and std::slist<T>.
Find Algorithms
Find algorithms have similar functionality to std::search() algorithm. They provide a different interface which is more suitable for common string operations. Instead of returning just the start of matching subsequence they return a range which is necessary when the length of the matching subsequence is not known beforehand. This feature also allows a partitioning of the input sequence into three parts: a prefix, a substring and a suffix.
Another difference is an addition of various searching methods besides find_first, including find_regex.
It the library, find algorithms are implemented in terms of Finders. Finders are used also by other facilities (replace,split). For convenience, there are also function wrappers for these finders to simplify find operations.
Currently the library contains only naive implementation of find algorithms with complexity O(n * m) where n is the size of the input sequence and m is the size of the search sequence. There are algorithms with complexity O(n), but for smaller sequence a constant overhead is rather big. For small m << n (m by magnitude smaller than n) the current implementation provides acceptable efficiency. Even the C++ standard defines the required complexity for search algorithm as O(n * m). It is possible that a future version of library will also contain algorithms with linear complexity as an option
Replace Algorithms
The implementation of replace algorithms follows the layered structure of the library. The lower layer implements generic substitution of a range in the input sequence. This layer takes a Finder object and a Formatter object as an input. These two functors define what to replace and what to replace it with. The upper layer functions are just wrapping calls to the lower layer. Finders are shared with the find and split facility.
As usual, the implementation of the lower layer is designed to work with a generic sequence while taking advantage of specific features if possible (by using Sequence traits)
Find Iterators & Split Algorithms
Find iterators are a logical extension of the find facility. Instead of searching for one match, the whole input can be iteratively searched for multiple matches. The result of the search is then used to partition the input. It depends on the algorithms which parts are returned as the result. They can be the matching parts (find_iterator) of the parts in between (split_iterator).
In addition the split algorithms like find_all() and split() can simplify the common operations. They use a find iterator to search the whole input and copy the matches they found into the supplied container.
Exception Safety
The library requires that all operations on types used as template or function arguments provide the basic exception-safety guarantee. In turn, all functions and algorithms in this library, except where stated otherwise, will provide the basic exception-safety guarantee. In other words: The library maintains its invariants and does not leak resources in the face of exceptions. Some library operations give stronger guarantees, which are documented on an individual basis.
Some functions can provide the strong exception-safety guarantee. That means that following statements are true: • If an exception is thrown, there are no effects other than those of the function • If an exception is thrown other than by the function, there are no effects This guarantee can be provided under the condition that the operations on the types used for arguments for these functions either provide the strong exception guarantee or do not alter the global state .
In the reference, under the term strong exception-safety guarantee, we mean the guarantee as defined above.
For more information about the exception safety topics, follow this link
Concepts
Concepts
Definitions
Table 13. Notation

F
A type that is a model of Finder
Fmt
A type that is a model of Formatter
Iter
Iterator Type
f
Object of type F
fmt
Object of type Fmt
i,j
Objects of type Iter

Finder Concept
Finder is a functor which searches for an arbitrary part of a container. The result of the search is given as an iterator_range delimiting the selected part.
Table 14. Valid Expressions

Expression
Return Type
Effects
f(i,j)
Convertible to iterator_range<Iter>
Perform the search on the interval [i,j) and returns the result of the search

Various algorithms need to perform a search in a container and a Finder is a generalization of such search operations that allows algorithms to abstract from searching. For instance, generic replace algorithms can replace any part of the input, and the Finder is used to select the desired one.
Note, that it is only required that the finder works with a particular iterator type. However, a Finder operation can be defined as a template, allowing the Finder to work with any iterator.
Examples
•
Finder implemented as a class. This Finder always returns the whole input as a match. operator() is templated, so that the finder can be used on any iterator type.

struct simple_finder { template<typename ForwardIteratorT> boost::iterator_range<ForwardIterator> operator()( ForwardIteratorT Begin, ForwardIteratorT End ) { return boost::make_range( Begin, End ); } };
•
Function Finder. Finder can be any function object. That is, any ordinary function with the required signature can be used as well. However, such a function can be used only for a specific iterator type.

boost::iterator_range<std::string> simple_finder( std::string::const_iterator Begin, std::string::const_iterator End ) { return boost::make_range( Begin, End ); }
Formatter concept
Formatters are used by replace algorithms. They are used in close combination with finders. A formatter is a functor, which takes a result from a Finder operation and transforms it in a specific way. The operation of the formatter can use additional information provided by a specific finder, for example regex_formatter() uses the match information from regex_finder() to format the result of formatter operation.
Table 15. Valid Expressions

Expression
Return Type
Effects
fmt(f(i,j))
A container type, accessible using container traits
Formats the result of the finder operation

Similarly to finders, formatters generalize format operations. When a finder is used to select a part of the input, formatter takes this selection and performs some formating on it. Algorithms can abstract from formating using a formatter.
Examples
•
Formatter implemented as a class. This Formatter does not perform any formating and returns the match, repackaged. operator() is templated, so that the Formatter can be used on any Finder type.

struct simple_formatter { template<typename FindResultT> std::string operator()( const FindResultT& Match ) { std::string Temp( Match.begin(), Match.end() ); return Temp; } };
•
Function Formatter. Similarly to Finder, Formatter can be any function object. However, as a function, it can be used only with a specific Finder type.

std::string simple_formatter( boost::iterator_range<std::string::const_iterator>& Match ) { std::string Temp( Match.begin(), Match.end() ); return Temp; }
Reference
Reference
Header <boost/algorithm/string/case_conv.hpp>
Defines sequence case-conversion algorithms. Algorithms convert each element in the input sequence to the desired case using provided locales.
namespace
boost { namespace algorithm { template<typename OutputIteratorT, typename CollectionT> OutputIteratorT to_lower_copy(OutputIteratorT, const CollectionT &, const std::locale & = std::locale()); template<typename SequenceT> SequenceT to_lower_copy(const SequenceT &, const std::locale & = std::locale()); template<typename MutableCollectionT> void to_lower(MutableCollectionT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename CollectionT> OutputIteratorT to_upper_copy(OutputIteratorT, const CollectionT &, const std::locale & = std::locale()); template<typename SequenceT> SequenceT to_upper_copy(const SequenceT &, const std::locale & = std::locale()); template<typename MutableCollectionT> void to_upper(MutableCollectionT &, const std::locale & = std::locale()); } }
Function to_lower_copy
Function to_lower_copy -- Convert to lower case.
boost::algorithm::to_lower_copy
template
<typename OutputIteratorT, typename CollectionT> OutputIteratorT to_lower_copy(OutputIteratorT Output, const CollectionT & Input, const std::locale & Loc = std::locale()); template<typename SequenceT> SequenceT to_lower_copy(const SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Each element of the input sequence is converted to lower case. The result is a copy of the input converted to lower case. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input collection
Loc
A locale used for conversion
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template to_lower
Function template to_lower -- Convert to lower case.
boost::algorithm::to_lower
template
<typename MutableCollectionT> void to_lower(MutableCollectionT & Input, const std::locale & Loc = std::locale());
Description
Description
Each element of the input sequence is converted to lower case. The input sequence is modified in-place.
Parameters
Input
A collection
Loc
a locale used for conversion
Function to_upper_copy
Function to_upper_copy -- Convert to upper case.
boost::algorithm::to_upper_copy
template
<typename OutputIteratorT, typename CollectionT> OutputIteratorT to_upper_copy(OutputIteratorT Output, const CollectionT & Input, const std::locale & Loc = std::locale()); template<typename SequenceT> SequenceT to_upper_copy(const SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Each element of the input sequence is converted to upper case. The result is a copy of the input converted to upper case. It is returned as a sequence or copied to the output iterator
Parameters
Input
An input collection
Loc
A locale used for conversion
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template to_upper
Function template to_upper -- Convert to upper case.
boost::algorithm::to_upper
template
<typename MutableCollectionT> void to_upper(MutableCollectionT & Input, const std::locale & Loc = std::locale());
Description
Description
Each element of the input sequence is converted to upper case. The input sequence is modified in-place.
Parameters
Input
An input collection
Loc
a locale used for conversion
Header <boost/algorithm/string/classification.hpp>
Classification predicates are included in the library to give some more convenience when using algorithms like trim() and all() . They wrap functionality of STL classification functions ( e.g. std::isspace() ) into generic functors.
namespace
boost { namespace algorithm { unspecified is_classified(std::ctype_base::mask, const std::locale & = std::locale()); unspecified is_space(const std::locale & = std::locale()); unspecified is_alnum(const std::locale & = std::locale()); unspecified is_alpha(const std::locale & = std::locale()); unspecified is_cntrl(const std::locale & = std::locale()); unspecified is_digit(const std::locale & = std::locale()); unspecified is_graph(const std::locale & = std::locale()); unspecified is_lower(const std::locale & = std::locale()); unspecified is_print(const std::locale & = std::locale()); unspecified is_punct(const std::locale & = std::locale()); unspecified is_upper(const std::locale & = std::locale()); unspecified is_xdigit(const std::locale & = std::locale()); template<typename ContainerT> unspecified is_any_of(const ContainerT &); template<typename CharT> unspecified is_from_range(CharT, CharT); template<typename Pred1T, typename Pred2T> unspecified operator&&(const predicate_facade< Pred1T > &, const predicate_facade< Pred2T > &); template<typename Pred1T, typename Pred2T> unspecified operator||(const predicate_facade< Pred1T > &, const predicate_facade< Pred2T > &); template<typename PredT> unspecified operator!(const predicate_facade< PredT > &); } }
Function is_classified
Function is_classified -- is_classified predicate
boost::algorithm::is_classified
unspecified
is_classified(std::ctype_base::mask Type, const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate. This predicate holds if the input is of specified std::ctype category.
Parameters
Loc
A locale used for classification
Type
A std::ctype category
Returns
An instance of the is_classified predicate
Function is_space
Function is_space -- is_space predicate
boost::algorithm::is_space
unspecified
is_space(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::space category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_alnum
Function is_alnum -- is_alnum predicate
boost::algorithm::is_alnum
unspecified
is_alnum(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::alnum category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_alpha
Function is_alpha -- is_alpha predicate
boost::algorithm::is_alpha
unspecified
is_alpha(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::alpha category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_cntrl
Function is_cntrl -- is_cntrl predicate
boost::algorithm::is_cntrl
unspecified
is_cntrl(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::cntrl category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_digit
Function is_digit -- is_digit predicate
boost::algorithm::is_digit
unspecified
is_digit(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::digit category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_graph
Function is_graph -- is_graph predicate
boost::algorithm::is_graph
unspecified
is_graph(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::graph category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_lower
Function is_lower -- is_lower predicate
boost::algorithm::is_lower
unspecified
is_lower(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::lower category.
Parameters
Loc
A locale used for classification
Returns
An instance of is_classified predicate
Function is_print
Function is_print -- is_print predicate
boost::algorithm::is_print
unspecified
is_print(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::print category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_punct
Function is_punct -- is_punct predicate
boost::algorithm::is_punct
unspecified
is_punct(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::punct category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_upper
Function is_upper -- is_upper predicate
boost::algorithm::is_upper
unspecified
is_upper(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::upper category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function is_xdigit
Function is_xdigit -- is_xdigit predicate
boost::algorithm::is_xdigit
unspecified
is_xdigit(const std::locale & Loc = std::locale());
Description
Description
Construct the is_classified predicate for the ctype_base::xdigit category.
Parameters
Loc
A locale used for classification
Returns
An instance of the is_classified predicate
Function template is_any_of
Function template is_any_of -- is_any_of predicate
boost::algorithm::is_any_of
template
<typename ContainerT> unspecified is_any_of(const ContainerT & Set);
Description
Description
Construct the is_any_of predicate. The predicate holds if the input is included in the specified set of characters.
Parameters
Set
A set of characters to be recognized
Returns
An instance of the is_any_of predicate
Function template is_from_range
Function template is_from_range -- is_from_range predicate
boost::algorithm::is_from_range
template
<typename CharT> unspecified is_from_range(CharT From, CharT To);
Description
Description
Construct the is_from_range predicate. The predicate holds if the input is included in the specified range. (i.e. From <= Ch <= To )
Parameters
From
The start of the range
To
The end of the range
Returns
An instance of the is_from_range predicate
Function template operator&&
Function template operator&& -- predicate 'and' composition predicate
boost::algorithm::operator&&
template
<typename Pred1T, typename Pred2T> unspecified operator&&(const predicate_facade< Pred1T > & Pred1, const predicate_facade< Pred2T > & Pred2);
Description
Description
Construct the class_and predicate. This predicate can be used to logically combine two classification predicates. class_and holds, if both predicates return true.
Parameters
Pred1
The first predicate
Pred2
The second predicate
Returns
An instance of the class_and predicate
Function template operator||
Function template operator|| -- predicate 'or' composition predicate
boost::algorithm::operator||
template
<typename Pred1T, typename Pred2T> unspecified operator||(const predicate_facade< Pred1T > & Pred1, const predicate_facade< Pred2T > & Pred2);
Description
Description
Construct the class_or predicate. This predicate can be used to logically combine two classification predicates. class_or holds, if one of the predicates return true.
Parameters
Pred1
The first predicate
Pred2
The second predicate
Returns
An instance of the class_or predicate
Function template operator!
Function template operator! -- predicate negation operator
boost::algorithm::operator!
template
<typename PredT> unspecified operator!(const predicate_facade< PredT > & Pred);
Description
Description
Construct the class_not predicate. This predicate represents a negation. class_or holds if of the predicates return false.
Parameters
Pred
The predicate to be negated
Returns
An instance of the class_not predicate
Header <boost/algorithm/string/collection_traits.hpp>
Defines collection_traits class and related free-standing functions. This facility is used to unify the access to different types of collections. It allows the algorithms in the library to work with STL collections, c-style array, null-terminated c-strings (and more) using the same interface.
namespace
boost { namespace algorithm { template<typename T> struct collection_traits; template<typename C> struct value_type_of; template<typename C> struct difference_type_of; template<typename C> struct iterator_of; template<typename C> struct const_iterator_of; template<typename C> struct result_iterator_of; template<typename C> collection_traits< C >::size_type size(const C &); template<typename C> bool empty(const C &); template<typename C> collection_traits< C >::iterator begin(C &); template<typename C> collection_traits< C >::const_iterator begin(const C &); template<typename C> collection_traits< C >::iterator end(C &); template<typename C> collection_traits< C >::const_iterator end(const C &); } }
Struct template collection_traits
Struct template collection_traits -- collection_traits class
boost::algorithm::collection_traits
template
<typename T> struct collection_traits { // types typedef container_helper_type function_type; // Function type. typedef container_helper_type::value_type value_type; // Value type. typedef container_helper_type::size_type size_type; // Size type. typedef container_helper_type::iterator iterator; // Iterator type. typedef container_helper_type::const_iterator const_iterator; // Const iterator type. typedef container_helper_type::result_iterator result_iterator; // Result iterator type ( iterator of const_iterator, depending on the constness of the container ). typedef container_helper_type::difference_type difference_type; // Difference type. };
Description
Description
Collection traits provide uniform access to different types of collections. This functionality allows to write generic algorithms which work with several different kinds of collections.
Currently following collection types are supported:•containers with STL compatible container interface ( see ContainerConcept ) ( i.e. std::vector<> , std::list<> , std::string<> ... )•c-style array ( char [10], int [15] ... )•null-terminated c-strings ( char* , wchar_T* )•std::pair of iterators ( i.e std::pair<vector<int>::iterator ,vector<int>::iterator> )
Collection traits provide an external collection interface operations. All are accessible using free-standing functions.
The following operations are supported:•size()•empty()•begin()•end()
Container traits have somewhat limited functionality on compilers not supporting partial template specialization and partial template ordering.
Struct template value_type_of
Struct template value_type_of -- Container value_type trait.
boost::algorithm::value_type_of
template
<typename C> struct value_type_of { // types typedef collection_traits< C >::value_type type; };
Description
Description
Extract the type of elements contained in a container
Struct template difference_type_of
Struct template difference_type_of -- Container difference trait.
boost::algorithm::difference_type_of
template
<typename C> struct difference_type_of { // types typedef collection_traits< C >::difference_type type; };
Description
Description
Extract the container's difference type
Struct template iterator_of
Struct template iterator_of -- Container iterator trait.
boost::algorithm::iterator_of
template
<typename C> struct iterator_of { // types typedef collection_traits< C >::iterator type; };
Description
Description
Extract the container's iterator type
Struct template const_iterator_of
Struct template const_iterator_of -- Container const_iterator trait.
boost::algorithm::const_iterator_of
template
<typename C> struct const_iterator_of { // types typedef collection_traits< C >::const_iterator type; };
Description
Description
Extract the container's const_iterator type
Struct template result_iterator_of
Struct template result_iterator_of -- Container result_iterator.
boost::algorithm::result_iterator_of
template
<typename C> struct result_iterator_of { // types typedef collection_traits< C >::result_iterator type; };
Description
Description
Extract the container's result_iterator type. This type maps to C::iterator for mutable container and C::const_iterator for const containers.
Function template size
Function template size -- Free-standing size() function.
boost::algorithm::size
template
<typename C> collection_traits< C >::size_type size(const C & c);
Description
Description
Get the size of the container. Uses collection_traits.
Function template empty
Function template empty -- Free-standing empty() function.
boost::algorithm::empty
template
<typename C> bool empty(const C & c);
Description
Description
Check whether the container is empty. Uses container traits.
Function begin
Function begin -- Free-standing begin() function.
boost::algorithm::begin
template
<typename C> collection_traits< C >::iterator begin(C & c); template<typename C> collection_traits< C >::const_iterator begin(const C & c);
Description
Description
Get the begin iterator of the container. Uses collection_traits.
Function end
Function end -- Free-standing end() function.
boost::algorithm::end
template
<typename C> collection_traits< C >::iterator end(C & c); template<typename C> collection_traits< C >::const_iterator end(const C & c);
Description
Description
Get the begin iterator of the container. Uses collection_traits.
Header <boost/algorithm/string/compare.hpp>
Defines element comparison predicates. Many algorithms in this library can take an additional argument with a predicate used to compare elements. This makes it possible, for instance, to have case insensitive versions of the algorithms.
namespace
boost { namespace algorithm { struct is_equal; struct is_iequal; } }
Struct is_equal
Struct is_equal -- is_equal functor
boost::algorithm::is_equal
struct
is_equal {

// public member functions
template
<typename T1, typename T2> bool operator()(const T1 &, const T2 &) const; };
Description
Description
Standard STL equal_to only handle comparison between arguments of the same type. This is a less restrictive version which wraps operator ==.
is_equal public member functions
is_equal
public member functions
1.
template
<typename T1, typename T2> bool operator()(const T1 & Arg1, const T2 & Arg2) const;
Compare two operands for equality
Struct is_iequal
Struct is_iequal -- case insensitive version of is_equal
boost::algorithm::is_iequal
struct
is_iequal { // construct/copy/destruct is_iequal(const std::locale & = std::locale());

// public member functions
template
<typename T1, typename T2> bool operator()(const T1 &, const T2 &) const; };
Description
Description
Case insensitive comparison predicate. Comparison is done using specified locales.
is_iequal construct/copy/destruct
is_iequal
construct/copy/destruct
1.
is_iequal(const std::locale & Loc = std::locale());
Parameters
Loc
locales used for comparison
is_iequal public member functions
is_iequal
public member functions
1.
template
<typename T1, typename T2> bool operator()(const T1 & Arg1, const T2 & Arg2) const;
Compare two operands. Case is ignored.
Header <boost/algorithm/string/concept.hpp>
Defines concepts used in string_algo library
namespace
boost { namespace algorithm { template<typename FinderT, typename IteratorT> struct FinderConcept; template<typename FormatterT, typename FinderT, typename IteratorT> struct FormatterConcept; } }
Struct template FinderConcept
Struct template FinderConcept -- Finder concept.
boost::algorithm::FinderConcept
template
<typename FinderT, typename IteratorT> struct FinderConcept {

// public member functions
void
constraints
() ; };
Description
Description
Defines the Finder concept. Finder is a functor which selects an arbitrary part of a string. Search is performed on the range specified by starting and ending iterators.
Result of the find operation must be convertible to iterator_range.
FinderConcept public member functions
FinderConcept
public member functions
1.
void
constraints() ;
Struct template FormatterConcept
Struct template FormatterConcept -- Formatter concept.
boost::algorithm::FormatterConcept
template
<typename FormatterT, typename FinderT, typename IteratorT> struct FormatterConcept {

// public member functions
void
constraints
() ; };
Description
Description
Defines the Formatter concept. Formatter is a functor, which takes a result from a finder operation and transforms it in a specific way.
Result must be a container supported by container_traits, or a reference to it.
FormatterConcept public member functions
FormatterConcept
public member functions
1.
void
constraints() ;
Header <boost/algorithm/string/constants.hpp>
namespace
boost { namespace algorithm { enum token_compress_mode_type; } }
Type token_compress_mode_type
Type token_compress_mode_type -- Token compression mode.
boost::algorithm::token_compress_mode_type
enum
token_compress_mode_type { token_compress_on, token_compress_off };
Header <boost/algorithm/string/erase.hpp>
Defines various erase algorithms. Each algorithm removes part(s) of the input according to a searching criteria.
namespace
boost { namespace algorithm { template<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_range_copy(OutputIteratorT, const CollectionT &, const iterator_range< typename const_iterator_of< CollectionT >::type > &); template<typename SequenceT> SequenceT erase_range_copy(const SequenceT &, const iterator_range< typename const_iterator_of< SequenceT >::type > &); template<typename SequenceT> void erase_range(SequenceT &, const iterator_range< typename iterator_of< SequenceT >::type > &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_first_copy(OutputIteratorT, const Collection1T &, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT erase_first_copy(const SequenceT &, const CollectionT &); template<typename SequenceT, typename CollectionT> void erase_first(SequenceT &, const CollectionT &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_first_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_first_copy(const SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> void ierase_first(SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_last_copy(OutputIteratorT, const Collection1T &, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT erase_last_copy(const SequenceT &, const CollectionT &); template<typename SequenceT, typename CollectionT> void erase_last(SequenceT &, const CollectionT &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_last_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_last_copy(const SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> void ierase_last(SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_nth_copy(OutputIteratorT, const Collection1T &, const Collection2T &, unsigned int); template<typename SequenceT, typename CollectionT> SequenceT erase_nth_copy(const SequenceT &, const CollectionT &, unsigned int); template<typename SequenceT, typename CollectionT> void erase_nth(SequenceT &, const CollectionT &, unsigned int); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_nth_copy(OutputIteratorT, const Collection1T &, const Collection2T &, unsigned int, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_nth_copy(const SequenceT &, const CollectionT &, unsigned int, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> void ierase_nth(SequenceT &, const CollectionT &, unsigned int, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_all_copy(OutputIteratorT, const Collection1T &, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT erase_all_copy(const SequenceT &, const CollectionT &); template<typename SequenceT, typename CollectionT> void erase_all(SequenceT &, const CollectionT &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_all_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_all_copy(const SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename SequenceT, typename CollectionT> void ierase_all(SequenceT &, const CollectionT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_head_copy(OutputIteratorT, const CollectionT &, unsigned int); template<typename SequenceT> SequenceT erase_head_copy(const SequenceT &, unsigned int); template<typename SequenceT> void erase_head(SequenceT &, unsigned int); template<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_tail_copy(OutputIteratorT, const CollectionT &, unsigned int); template<typename SequenceT> SequenceT erase_tail_copy(const SequenceT &, unsigned int); template<typename SequenceT> void erase_tail(SequenceT &, unsigned int); } }
Function erase_range_copy
Function erase_range_copy -- Erase range algorithm.
boost::algorithm::erase_range_copy
template
<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_range_copy(OutputIteratorT Output, const CollectionT & Input, const iterator_range< typename const_iterator_of< CollectionT >::type > & SearchRange); template<typename SequenceT> SequenceT erase_range_copy(const SequenceT & Input, const iterator_range< typename const_iterator_of< SequenceT >::type > & SearchRange);
Description
Description
Remove the given range from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input sequence
Output
An output iterator to which the result will be copied
SearchRange
A range in the input to be removed
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_range
Function template erase_range -- Erase range algorithm.
boost::algorithm::erase_range
template
<typename SequenceT> void erase_range(SequenceT & Input, const iterator_range< typename iterator_of< SequenceT >::type > & SearchRange);
Description
Description
Remove the given range from the input. The input sequence is modified in-place.
Parameters
Input
An input sequence
SearchRange
A range in the input to be removed
Function erase_first_copy
Function erase_first_copy -- Erase first algorithm.
boost::algorithm::erase_first_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_first_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search); template<typename SequenceT, typename CollectionT> SequenceT erase_first_copy(const SequenceT & Input, const CollectionT & Search);
Description
Description
Remove the first occurence of the substring from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input string
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_first
Function template erase_first -- Erase first algorithm.
boost::algorithm::erase_first
template
<typename SequenceT, typename CollectionT> void erase_first(SequenceT & Input, const CollectionT & Search);
Description
Description
Remove the first occurence of the substring from the input. The input sequence is modified in-place.
Parameters
Input
An input string
Search
A substring to be searched for.
Function ierase_first_copy
Function ierase_first_copy -- Erase first algorithm ( case insensitive ).
boost::algorithm::ierase_first_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_first_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_first_copy(const SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove the first occurence of the substring from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ierase_first
Function template ierase_first -- Erase first algorithm ( case insensitive ).
boost::algorithm::ierase_first
template
<typename SequenceT, typename CollectionT> void ierase_first(SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove the first occurence of the substring from the input. The input sequence is modified in-place. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for
Function erase_last_copy
Function erase_last_copy -- Erase last algorithm.
boost::algorithm::erase_last_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_last_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search); template<typename SequenceT, typename CollectionT> SequenceT erase_last_copy(const SequenceT & Input, const CollectionT & Search);
Description
Description
Remove the last occurence of the substring from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input string
Output
An output iterator to which the result will be copied
Search
A substring to be searched for.
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_last
Function template erase_last -- Erase last algorithm.
boost::algorithm::erase_last
template
<typename SequenceT, typename CollectionT> void erase_last(SequenceT & Input, const CollectionT & Search);
Description
Description
Remove the last occurence of the substring from the input. The input sequence is modified in-place.
Parameters
Input
An input string
Search
A substring to be searched for
Function ierase_last_copy
Function ierase_last_copy -- Erase last algorithm ( case insensitive ).
boost::algorithm::ierase_last_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_last_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_last_copy(const SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove the last occurence of the substring from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ierase_last
Function template ierase_last -- Erase last algorithm ( case insensitive ).
boost::algorithm::ierase_last
template
<typename SequenceT, typename CollectionT> void ierase_last(SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove the last occurence of the substring from the input. The input sequence is modified in-place. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for
Function erase_nth_copy
Function erase_nth_copy -- Erase nth algorithm.
boost::algorithm::erase_nth_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_nth_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, unsigned int Nth); template<typename SequenceT, typename CollectionT> SequenceT erase_nth_copy(const SequenceT & Input, const CollectionT & Search, unsigned int Nth);
Description
Description
Remove the Nth occurence of the substring in the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input string
Nth
An index of the match to be replaced. The index is 0-based.
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_nth
Function template erase_nth -- Erase nth algorithm.
boost::algorithm::erase_nth
template
<typename SequenceT, typename CollectionT> void erase_nth(SequenceT & Input, const CollectionT & Search, unsigned int Nth);
Description
Description
Remove the Nth occurence of the substring in the input. The input sequence is modified in-place.
Parameters
Input
An input string
Nth
An index of the match to be replaced. The index is 0-based.
Search
A substring to be searched for.
Function ierase_nth_copy
Function ierase_nth_copy -- Erase nth algorithm ( case insensitive ).
boost::algorithm::ierase_nth_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_nth_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, unsigned int Nth, const std::locale & Loc = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_nth_copy(const SequenceT & Input, const CollectionT & Search, unsigned int Nth, const std::locale & Loc = std::locale());
Description
Description
Remove the Nth occurence of the substring in the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Nth
An index of the match to be replaced. The index is 0-based.
Output
An output iterator to which the result will be copied
Search
A substring to be searched for.
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ierase_nth
Function template ierase_nth -- Erase nth algorithm.
boost::algorithm::ierase_nth
template
<typename SequenceT, typename CollectionT> void ierase_nth(SequenceT & Input, const CollectionT & Search, unsigned int Nth, const std::locale & Loc = std::locale());
Description
Description
Remove the Nth occurence of the substring in the input. The input sequence is modified in-place. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Nth
An index of the match to be replaced. The index is 0-based.
Search
A substring to be searched for.
Function erase_all_copy
Function erase_all_copy -- Erase all algorithm.
boost::algorithm::erase_all_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT erase_all_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search); template<typename SequenceT, typename CollectionT> SequenceT erase_all_copy(const SequenceT & Input, const CollectionT & Search);
Description
Description
Remove all the occurrences of the string from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input sequence
Output
An output iterator to which the result will be copied
Search
A substring to be searched for.
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_all
Function template erase_all -- Erase all algorithm.
boost::algorithm::erase_all
template
<typename SequenceT, typename CollectionT> void erase_all(SequenceT & Input, const CollectionT & Search);
Description
Description
Remove all the occurrences of the string from the input. The input sequence is modified in-place.
Parameters
Input
An input string
Search
A substring to be searched for.
Function ierase_all_copy
Function ierase_all_copy -- Erase all algorithm ( case insensitive ).
boost::algorithm::ierase_all_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT ierase_all_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale()); template<typename SequenceT, typename CollectionT> SequenceT ierase_all_copy(const SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove all the occurrences of the string from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ierase_all
Function template ierase_all -- Erase all algorithm ( case insensitive ).
boost::algorithm::ierase_all
template
<typename SequenceT, typename CollectionT> void ierase_all(SequenceT & Input, const CollectionT & Search, const std::locale & Loc = std::locale());
Description
Description
Remove all the occurrences of the string from the input. The input sequence is modified in-place. Searching is case insensitive.
Parameters
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for.
Function erase_head_copy
Function erase_head_copy -- Erase head algorithm.
boost::algorithm::erase_head_copy
template
<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_head_copy(OutputIteratorT Output, const CollectionT & Input, unsigned int N); template<typename SequenceT> SequenceT erase_head_copy(const SequenceT & Input, unsigned int N);
Description
Description
Remove the head from the input. The head is a prefix of a seqence of given size. If the sequence is shorter then required, the whole string is considered to be the head. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input string
N
Length of the head
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_head
Function template erase_head -- Erase head algorithm.
boost::algorithm::erase_head
template
<typename SequenceT> void erase_head(SequenceT & Input, unsigned int N);
Description
Description
Remove the head from the input. The head is a prefix of a seqence of given size. If the sequence is shorter then required, the whole string is considered to be the head. The input sequence is modified in-place.
Parameters
Input
An input string
N
Length of the head
Function erase_tail_copy
Function erase_tail_copy -- Erase tail algorithm.
boost::algorithm::erase_tail_copy
template
<typename OutputIteratorT, typename CollectionT> OutputIteratorT erase_tail_copy(OutputIteratorT Output, const CollectionT & Input, unsigned int N); template<typename SequenceT> SequenceT erase_tail_copy(const SequenceT & Input, unsigned int N);
Description
Description
Remove the tail from the input. The tail is a suffix of a seqence of given size. If the sequence is shorter then required, the whole string is considered to be the tail. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Input
An input string
N
Length of the head
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_tail
Function template erase_tail -- Erase tail algorithm.
boost::algorithm::erase_tail
template
<typename SequenceT> void erase_tail(SequenceT & Input, unsigned int N);
Description
Description
Remove the tail from the input. The tail is a suffix of a seqence of given size. If the sequence is shorter then required, the whole string is considered to be the tail. The input sequence is modified in-place.
Parameters
Input
An input string
N
Length of the head
Header <boost/algorithm/string/find.hpp>
Defines a set of find algorithms. The algorithms are searching for a substring of the input. The result is given as an iterator_range delimiting the substring.
namespace
boost { namespace algorithm { template<typename CollectionT, typename FinderT> iterator_range< typename result_iterator_of< CollectionT >::type > find(CollectionT &, FinderT); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_first(Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_first(Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_last(Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_last(Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_nth(Collection1T &, const Collection2T &, unsigned int); template<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_nth(Collection1T &, const Collection2T &, unsigned int, const std::locale & = std::locale()); template<typename CollectionT> iterator_range< typename result_iterator_of< CollectionT >::type > find_head(CollectionT &, unsigned int); template<typename CollectionT> iterator_range< typename result_iterator_of< CollectionT >::type > find_tail(CollectionT &, unsigned int); template<typename CollectionT, typename PredicateT> iterator_range< typename result_iterator_of< CollectionT >::type > find_token(CollectionT &, PredicateT, token_compress_mode_type = token_compress_off); } }
Function template find
Function template find -- Generic find algorithm.
boost::algorithm::find
template
<typename CollectionT, typename FinderT> iterator_range< typename result_iterator_of< CollectionT >::type > find(CollectionT & Input, FinderT Finder);
Description
Description
Search the input using the given finder.
Parameters
Finder
Finder object used for searching.
Input
A string which will be searched.
Returns
An iterator_range delimiting the match. Returned iterator is either CollectionT::iterator or CollectionT::const_iterator , depending on the constness of the input parameter.
Function template find_first
Function template find_first -- Find first algorithm.
boost::algorithm::find_first
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_first(Collection1T & Input, const Collection2T & Search);
Description
Description
Search for the first occurence of the substring in the input.
Parameters
Input
A string which will be searched.
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either CollectionT::iterator or CollectionT::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template ifind_first
Function template ifind_first -- Find first algorithm ( case insensitive ).
boost::algorithm::ifind_first
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_first(Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale());
Description
Description
Search for the first occurence of the substring in the input. Searching is case insensitive.
Parameters
Input
A string which will be searched.
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template find_last
Function template find_last -- Find last algorithm.
boost::algorithm::find_last
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_last(Collection1T & Input, const Collection2T & Search);
Description
Description
Search for the last occurence of the substring in the input.
Parameters
Input
A string which will be searched.
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template ifind_last
Function template ifind_last -- Find last algorithm ( case insensitive ).
boost::algorithm::ifind_last
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_last(Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale());
Description
Description
Search for the last match a string in the input. Searching is case insensitive.
Parameters
Input
A string which will be searched.
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template find_nth
Function template find_nth -- Find n-th algorithm.
boost::algorithm::find_nth
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > find_nth(Collection1T & Input, const Collection2T & Search, unsigned int Nth);
Description
Description
Search for the n-th (zero-indexed) occurence of the substring in the input.
Parameters
Input
A string which will be searched.
Nth
An index (zero-indexed) of the match to be found.
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Function template ifind_nth
Function template ifind_nth -- Find n-th algorithm ( case insensitive ).
boost::algorithm::ifind_nth
template
<typename Collection1T, typename Collection2T> iterator_range< typename result_iterator_of< Collection1T >::type > ifind_nth(Collection1T & Input, const Collection2T & Search, unsigned int Nth, const std::locale & Loc = std::locale());
Description
Description
Search for the n-th (zero-indexed) occurence of the substring in the input. Searching is case insensitive.
Parameters
Input
A string which will be searched.
Loc
A locale used for case insensitive comparison
Nth
An index (zero-indexed) of the match to be found.
Search
A substring to be searched for.
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template find_head
Function template find_head -- Find head algorithm.
boost::algorithm::find_head
template
<typename CollectionT> iterator_range< typename result_iterator_of< CollectionT >::type > find_head(CollectionT & Input, unsigned int N);
Description
Description
Get the head of the input. Head is a prefix of the string of the given size. If the input is shorter then required, whole input if considered to be the head.
Parameters
Input
An input string
N
Length of the head
Returns
An iterator_range delimiting the match. Returned iterator is either Collection1T::iterator or Collection1T::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template find_tail
Function template find_tail -- Find tail algorithm.
boost::algorithm::find_tail
template
<typename CollectionT> iterator_range< typename result_iterator_of< CollectionT >::type > find_tail(CollectionT & Input, unsigned int N);
Description
Description
Get the head of the input. Head is a suffix of the string of the given size. If the input is shorter then required, whole input if considered to be the tail.
Parameters
Input
An input string
N
Length of the tail
Returns
An iterator_range delimiting the match. Returned iterator is either CollectionT::iterator or CollectionT::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function template find_token
Function template find_token -- Find token algorithm.
boost::algorithm::find_token
template
<typename CollectionT, typename PredicateT> iterator_range< typename result_iterator_of< CollectionT >::type > find_token(CollectionT & Input, PredicateT Pred, token_compress_mode_type eCompress = token_compress_off);
Description
Description
Look for a given token in the string. Token is a character that matches the given predicate. If the "token compress mode" is enabled, adjacent tokens are considered to be one match.
Parameters
Input
A input string.
Pred
An unary predicate to identify a token
eCompress
Enable/Disable compressing of adjacent tokens
Returns
An iterator_range delimiting the match. Returned iterator is either CollectionT::iterator or CollectionT::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Header <boost/algorithm/string/find_format.hpp>
Defines generic replace algorithms. Each algorithm replaces part(s) of the input. The part to be replaced is looked up using a Finder object. Result of finding is then used by a Formatter object to generate the replacement.
namespace
boost { namespace algorithm { template<typename OutputIteratorT, typename CollectionT, typename FinderT, typename FormatterT> OutputIteratorT find_format_copy(OutputIteratorT, const CollectionT &, FinderT, FormatterT); template<typename SequenceT, typename FinderT, typename FormatterT> SequenceT find_format_copy(const SequenceT &, FinderT, FormatterT); template<typename SequenceT, typename FinderT, typename FormatterT> void find_format(SequenceT &, FinderT, FormatterT); template<typename OutputIteratorT, typename CollectionT, typename FinderT, typename FormatterT> OutputIteratorT find_format_all_copy(OutputIteratorT, const CollectionT &, FinderT, FormatterT); template<typename SequenceT, typename FinderT, typename FormatterT> SequenceT find_format_all_copy(const SequenceT &, FinderT, FormatterT); template<typename SequenceT, typename FinderT, typename FormatterT> void find_format_all(SequenceT &, FinderT, FormatterT); template<typename CharT, typename RegexTraitsT, typename RegexAllocatorT> unspecified regex_finder(const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename CharT, typename TraitsT, typename AllocT> unspecified regex_formatter(const std::basic_string< CharT, TraitsT, AllocT > &, match_flag_type = format_default); } }
Function find_format_copy
Function find_format_copy -- Generic replace algorithm.
boost::algorithm::find_format_copy
template
<typename OutputIteratorT, typename CollectionT, typename FinderT, typename FormatterT> OutputIteratorT find_format_copy(OutputIteratorT Output, const CollectionT & Input, FinderT Finder, FormatterT Formatter); template<typename SequenceT, typename FinderT, typename FormatterT> SequenceT find_format_copy(const SequenceT & Input, FinderT Finder, FormatterT Formatter);
Description
Description
Use the Finder to search for a substring. Use the Formatter to format this substring and replace it in the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Finder
A Finder object used to search for a match to be replaced
Formatter
A Formatter object used to format a match
Input
An input sequence
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template find_format
Function template find_format -- Generic replace algorithm.
boost::algorithm::find_format
template
<typename SequenceT, typename FinderT, typename FormatterT> void find_format(SequenceT & Input, FinderT Finder, FormatterT Formatter);
Description
Description
Use the Finder to search for a substring. Use the Formatter to format this substring and replace it in the input. The input is modified in-place.
Parameters
Finder
A Finder object used to search for a match to be replaced
Formatter
A Formatter object used to format a match
Input
An input sequence
Function find_format_all_copy
Function find_format_all_copy -- Generic replace all algorithm.
boost::algorithm::find_format_all_copy
template
<typename OutputIteratorT, typename CollectionT, typename FinderT, typename FormatterT> OutputIteratorT find_format_all_copy(OutputIteratorT Output, const CollectionT & Input, FinderT Finder, FormatterT Formatter); template<typename SequenceT, typename FinderT, typename FormatterT> SequenceT find_format_all_copy(const SequenceT & Input, FinderT Finder, FormatterT Formatter);
Description
Description
Use the Finder to search for a substring. Use the Formatter to format this substring and replace it in the input. Repeat this for all matching substrings. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Finder
A Finder object used to search for a match to be replaced
Formatter
A Formatter object used to format a match
Input
An input sequence
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template find_format_all
Function template find_format_all -- Generic replace all algorithm.
boost::algorithm::find_format_all
template
<typename SequenceT, typename FinderT, typename FormatterT> void find_format_all(SequenceT & Input, FinderT Finder, FormatterT Formatter);
Description
Description
Use the Finder to search for a substring. Use the Formatter to format this substring and replace it in the input. Repeat this for all matching substrings.The input is modified in-place.
Parameters
Finder
A Finder object used to search for a match to be replaced
Formatter
A Formatter object used to format a match
Input
An input sequence
Function template regex_finder
Function template regex_finder -- "Regex" finder
boost::algorithm::regex_finder
template
<typename CharT, typename RegexTraitsT, typename RegexAllocatorT> unspecified regex_finder(const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type MatchFlags = match_default);
Description
Description
Construct the regex_finder . Finder uses the regex engine to search for a match. Result is given in regex_search_result . This is an extension of the iterator_range. In addition it containes match results from the regex_search algorithm.
Parameters
MatchFlags
Regex search options
Rx
A regular expression
Returns
An instance of the regex_finder object
Function template regex_formatter
Function template regex_formatter -- Regex formatter.
boost::algorithm::regex_formatter
template
<typename CharT, typename TraitsT, typename AllocT> unspecified regex_formatter(const std::basic_string< CharT, TraitsT, AllocT > & Format, match_flag_type Flags = format_default);
Description
Description
Construct the regex_formatter . Regex formatter uses the regex engine to format a match found by the regex_finder . This formatted it designed to closely cooperate with regex_finder .
Parameters
Flags
Format flags
Format
Regex format definition
Returns
An instance of the regex_formatter functor
Header <boost/algorithm/string/find_iterator.hpp>
Defines find iterator classes. Find iterator repeatly applies a Finder to the specified input string to search for matches. Dereferencing the iterator yields the current match or a range between the last and the current match depending on the iterator used.
namespace
boost { namespace algorithm { template<typename IteratorT> class find_iterator; template<typename IteratorT> class split_iterator; template<typename CollectionT, typename FinderT> find_iterator< typename result_iterator_of< CollectionT >::type > make_find_iterator(CollectionT &, FinderT); template<typename CollectionT, typename FinderT> split_iterator< typename result_iterator_of< CollectionT >::type > make_split_iterator(CollectionT &, FinderT); } }
Class template find_iterator
Class template find_iterator -- find_iterator
boost::algorithm::find_iterator
template
<typename IteratorT> class find_iterator { public: // construct/copy/destruct find_iterator(); find_iterator(const find_iterator &); template<typename FinderT> find_iterator(IteratorT, IteratorT, FinderT); template<typename FinderT, typename CollectionT> find_iterator(CollectionT &, FinderT);

// public member functions
bool
eof
() const;

// private member functions
const
match_type & dereference() const; void increment() ; bool equal(const find_iterator &) const; };
Description
Description
Find iterator encapsulates a Finder and allows for incremental searching in a string. Each increment moves the iterator to the next match.
Find iterator is a readable forward traversal iterator.
Dereferencing the iterator yields an iterator_range delimiting the current match.
find_iterator construct/copy/destruct
find_iterator
construct/copy/destruct
1.
find_iterator();
Construct null iterator. All null iterators are equal.
Postconditions
eof()==true
2.
find_iterator(const find_iterator & Other);
Construct a copy of the find_iterator
3.
template
<typename FinderT> find_iterator(IteratorT Begin, IteratorT End, FinderT Finder);
Construct new find_iterator for a given finder and a range.
4.
template
<typename FinderT, typename CollectionT> find_iterator(CollectionT & Col, FinderT Finder);
Construct new find_iterator for a given finder and a collection.
find_iterator public member functions
find_iterator
public member functions
1.
bool
eof() const;
Check the eof condition. Eof condition means that there is nothing more to be searched i.e. find_iterator is after the last match.
find_iterator private member functions
find_iterator
private member functions
1.
const
match_type & dereference() const;
2.
void
increment() ;
3.
bool
equal(const find_iterator & Other) const;
Class template split_iterator
Class template split_iterator -- split_iterator
boost::algorithm::split_iterator
template
<typename IteratorT> class split_iterator { public: // construct/copy/destruct split_iterator(); split_iterator(const split_iterator &); template<typename FinderT> split_iterator(IteratorT, IteratorT, FinderT); template<typename FinderT, typename CollectionT> split_iterator(CollectionT &, FinderT);

// public member functions
bool
eof
() const;

// private member functions
const
match_type & dereference() const; void increment() ; bool equal(const split_iterator &) const; };
Description
Description
Split iterator encapsulates a Finder and allows for incremental searching in a string. Unlike the find iterator, split iterator iterates through gaps between matches.
Find iterator is a readable forward traversal iterator.
Dereferencing the iterator yields an iterator_range delimiting the current match.
split_iterator construct/copy/destruct
split_iterator
construct/copy/destruct
1.
split_iterator();
Construct null iterator. All null iterators are equal.
Postconditions
eof()==true
2.
split_iterator(const split_iterator & Other);
Construct a copy of the split_iterator
3.
template
<typename FinderT> split_iterator(IteratorT Begin, IteratorT End, FinderT Finder);
Construct new split_iterator for a given finder and a range.
4.
template
<typename FinderT, typename CollectionT> split_iterator(CollectionT & Col, FinderT Finder);
Construct new split_iterator for a given finder and a collection.
split_iterator public member functions
split_iterator
public member functions
1.
bool
eof() const;
Check the eof condition. Eof condition means that there is nothing more to be searched i.e. find_iterator is after the last match.
split_iterator private member functions
split_iterator
private member functions
1.
const
match_type & dereference() const;
2.
void
increment() ;
3.
bool
equal(const split_iterator & Other) const;
Function template make_find_iterator
Function template make_find_iterator -- find iterator construction helper
boost::algorithm::make_find_iterator
template
<typename CollectionT, typename FinderT> find_iterator< typename result_iterator_of< CollectionT >::type > make_find_iterator(CollectionT & Collection, FinderT Finder);
Description
Description
Construct a find iterator to iterate through the specified string
Function template make_split_iterator
Function template make_split_iterator -- split iterator construction helper
boost::algorithm::make_split_iterator
template
<typename CollectionT, typename FinderT> split_iterator< typename result_iterator_of< CollectionT >::type > make_split_iterator(CollectionT & Collection, FinderT Finder);
Description
Description
Construct a split iterator to iterate through the specified collection
Header <boost/algorithm/string/finder.hpp>
Defines Finder generators. Finder object is a functor which is able to find a substring matching a specific criteria in the input. Finders are used as a pluggable components for replace, find and split facilities. This header contains generator functions for finders provided in this library.
namespace
boost { namespace algorithm { template<typename ContainerT> unspecified first_finder(const ContainerT &); template<typename ContainerT, typename PredicateT> unspecified first_finder(const ContainerT &, PredicateT); template<typename ContainerT> unspecified last_finder(const ContainerT &); template<typename ContainerT, typename PredicateT> unspecified last_finder(const ContainerT &, PredicateT); template<typename ContainerT> unspecified nth_finder(const ContainerT &, unsigned int); template<typename ContainerT, typename PredicateT> unspecified nth_finder(const ContainerT &, unsigned int, PredicateT); unspecified head_finder(unsigned int); unspecified tail_finder(unsigned int); template<typename PredicateT> unspecified token_finder(PredicateT, token_compress_mode_type = token_compress_off); template<typename ForwardIteratorT> unspecified range_finder(ForwardIteratorT, ForwardIteratorT); template<typename ForwardIteratorT> unspecified range_finder(iterator_range< ForwardIteratorT >); } }
Function first_finder
Function first_finder -- "First" finder
boost::algorithm::first_finder
template
<typename ContainerT> unspecified first_finder(const ContainerT & Search); template<typename ContainerT, typename PredicateT> unspecified first_finder(const ContainerT & Search, PredicateT Comp);
Description
Description
Construct the first_finder . The finder searches for the first occurrence of the string in a given input. The result is given as an iterator_range delimiting the match.
Parameters
Search
A substring to be searched for.
Returns
An instance of the first_finder object
Function last_finder
Function last_finder -- "Last" finder
boost::algorithm::last_finder
template
<typename ContainerT> unspecified last_finder(const ContainerT & Search); template<typename ContainerT, typename PredicateT> unspecified last_finder(const ContainerT & Search, PredicateT Comp);
Description
Description
Construct the last_finder . The finder searches for the last occurrence of the string in a given input. The result is given as an iterator_range delimiting the match.
Parameters
Search
A substring to be searched for.
Returns
An instance of the last_finder object
Function nth_finder
Function nth_finder -- "Nth" finder
boost::algorithm::nth_finder
template
<typename ContainerT> unspecified nth_finder(const ContainerT & Search, unsigned int Nth); template<typename ContainerT, typename PredicateT> unspecified nth_finder(const ContainerT & Search, unsigned int Nth, PredicateT Comp);
Description
Description
Construct the nth_finder . The finder searches for the n-th (zero-indexed) occurrence of the string in a given input. The result is given as an iterator_range delimiting the match.
Parameters
Nth
An index of the match to be find
Search
A substring to be searched for.
Returns
An instance of the nth_finder object
Function head_finder
Function head_finder -- "Head" finder
boost::algorithm::head_finder
unspecified
head_finder(unsigned int N);
Description
Description
Construct the head_finder . The finder returns a head of a given input. The head is a prefix of a string up to n elements in size. If an input has less then n elements, whole input is considered a head. The result is given as an iterator_range delimiting the match.
Parameters
N
The size of the head
Returns
An instance of the head_finder object
Function tail_finder
Function tail_finder -- "Tail" finder
boost::algorithm::tail_finder
unspecified
tail_finder(unsigned int N);
Description
Description
Construct the tail_finder . The finder returns a tail of a given input. The tail is a suffix of a string up to n elements in size. If an input has less then n elements, whole input is considered a head. The result is given as an iterator_range delimiting the match.
Parameters
N
The size of the head
Returns
An instance of the tail_finder object
Function template token_finder
Function template token_finder -- "Token" finder
boost::algorithm::token_finder
template
<typename PredicateT> unspecified token_finder(PredicateT Pred, token_compress_mode_type eCompress = token_compress_off);
Description
Description
Construct the token_finder . The finder searches for a token specified by a predicate. It is similar to std::find_if algorithm, with an exception that it return a range of instead of a single iterator.
If "compress token mode" is enabled, adjacent matching tokens are concatenated into one match. Thus the finder can be used to search for continuous segments of characters satisfying the given predicate.
The result is given as an iterator_range delimiting the match.
Parameters
Pred
An element selection predicate
eCompress
Compress flag
Returns
An instance of the token_finder object
Function range_finder
Function range_finder -- "Range" finder
boost::algorithm::range_finder
template
<typename ForwardIteratorT> unspecified range_finder(ForwardIteratorT Begin, ForwardIteratorT End); template<typename ForwardIteratorT> unspecified range_finder(iterator_range< ForwardIteratorT > Range);
Description
Description
Construct the range_finder . The finder does not perform any operation. It simply returns the given range for any input.
Parameters
Begin
Beginning of the range
End
End of the range
Returns
An instance of the range_finger object
Header <boost/algorithm/string/formatter.hpp>
Defines Formatter generators. Formatter is a functor which formats a string according to given parameters. A Formatter works in conjunction with a Finder. A Finder can provide additional information for a specific Formatter. An example of such a cooperation is regex_finder and regex_formatter.
Formatters are used as pluggable components for replace facilities. This header contains generator functions for the Formatters provided in this library.
namespace
boost { namespace algorithm { template<typename CollectionT> unspecified const_formatter(const CollectionT &); template<typename CollectionT> unspecified identity_formatter(); template<typename CollectionT> unspecified empty_formatter(const CollectionT &); } }
Function template const_formatter
Function template const_formatter -- Constant formatter.
boost::algorithm::const_formatter
template
<typename CollectionT> unspecified const_formatter(const CollectionT & Format);
Description
Description
Construct the const_formatter . Const formatter always returns the same value, regardless of the parameter.
Parameters
Format
A predefined value used as a result for formating
Returns
An instance of the const_formatter object.
Function template identity_formatter
Function template identity_formatter -- Identity formatter.
boost::algorithm::identity_formatter
template
<typename CollectionT> unspecified identity_formatter();
Description
Description
Construct the identity_formatter . Identity formatter always returns the parameter.
Returns
An instance of the identity_formatter object.
Function template empty_formatter
Function template empty_formatter -- Empty formatter.
boost::algorithm::empty_formatter
template
<typename CollectionT> unspecified empty_formatter(const CollectionT & );
Description
Description
Construct the empty_formatter . Empty formater always returns an empty sequence.
Returns
An instance of the empty_formatter object.
Header <boost/algorithm/string/iterator_range.hpp>
Defines the iterator_class and related functions. iterator_range is a simple wrapper of the iterator pair idiom. It provides a rich subset of the Container interface.
namespace
boost { namespace algorithm { template<typename IteratorT> class iterator_range; template<typename IteratorT, typename Elem, typename Traits> std::basic_ostream< Elem, Traits > & operator<<(std::basic_ostream< Elem, Traits > &, const iterator_range< IteratorT > &); template<typename IteratorT> iterator_range< IteratorT > make_iterator_range(IteratorT, IteratorT); template<typename IteratorT> iterator_range< IteratorT > make_iterator_range(const std::pair< IteratorT, IteratorT > &); template<typename SeqT, typename IteratorT> SeqT copy_iterator_range(const iterator_range< IteratorT > &); template<typename SeqT, typename IteratorT, typename FuncT> SeqT transform_iterator_range(const iterator_range< IteratorT > &, FuncT); } }
Class template iterator_range
Class template iterator_range -- iterator_range class
boost::algorithm::iterator_range
template
<typename IteratorT> class iterator_range { public: // types typedef iterator_range< IteratorT > type; // this type typedef unspecified value_type; // Encapsulated value type. typedef unspecified reference; // Reference type. typedef unspecified difference_type; // Difference type. typedef unspecified size_type; // Size type. typedef IteratorT const_iterator; // const_iterator type typedef IteratorT iterator; // iterator type typedef iterator(iterator_range::* unspecified_bool_type; // Safe bool conversion.

// construct/copy/destruct
iterator_range
(); iterator_range(iterator, iterator); iterator_range(const std::pair< IteratorT, IteratorT > &); iterator_range(const iterator_range &); template<typename OtherItT> iterator_range(const iterator_range< OtherItT > &); iterator_range& operator=(const iterator_range &); template<typename OtherItT> iterator_range& operator=(const iterator_range< OtherItT > &);

// public member functions
template
<typename OtherItT> bool operator==(const iterator_range< OtherItT > &) const; template<typename OtherItT> bool operator!=(const iterator_range< OtherItT > &) const; IteratorT begin() const; IteratorT end() const; bool empty() const; difference_type size() const; void swap(iterator_range &) ; operator unspecified_bool_type() const; };
Description
Description
An iterator_range delimits a range in a sequence by beginning and ending iterators. An iterator_range can be passed to an algorithm which requires a sequence as an input. For example, the toupper() function may most frequently be used on strings, but can also be used on iterator_ranges:
boost::tolower( find( s, "UPPERCASE STRING" ) );
Many algorithms working with sequences take a pair of iterators, delimiting a working range, as arguments. The iterator_range class is an encapsulation of a range identified by a pair of iterators. It provides a collection interface, so it is possible to pass an instance to an algorithm requiring a collection as an input.
iterator_range construct/copy/destruct
iterator_range
construct/copy/destruct
1.
iterator_range();
2.
iterator_range(iterator Begin, iterator End);
3.
iterator_range(const std::pair< IteratorT, IteratorT > & Range);
4.
iterator_range(const iterator_range & Other);
5.
template
<typename OtherItT> iterator_range(const iterator_range< OtherItT > & Other);
This constructor is provided to allow conversion between const and mutable iterator instances of this class template
6.
iterator_range& operator=(const iterator_range & Other);
7.
template
<typename OtherItT> iterator_range& operator=(const iterator_range< OtherItT > & Other);
iterator_range public member functions
iterator_range
public member functions
1.
template
<typename OtherItT> bool operator==(const iterator_range< OtherItT > & Other) const;
Compare operands for equality
2.
template
<typename OtherItT> bool operator!=(const iterator_range< OtherItT > & Other) const;
Compare operands for non-equality
3.
IteratorT begin() const;
Retrieve the begin iterator
4.
IteratorT end() const;
Retrieve the end iterator
5.
bool
empty() const;
Test whether the range is empty
6.
difference_type size() const;
Retrieve the size of the range
7.
void
swap(iterator_range & Other) ;
Swap two ranges
8.
operator
unspecified_bool_type() const;
Function template operator<<
Function template operator<< -- iterator_range output operator
boost::algorithm::operator<<
template
<typename IteratorT, typename Elem, typename Traits> std::basic_ostream< Elem, Traits > & operator<<(std::basic_ostream< Elem, Traits > & Os, const iterator_range< IteratorT > & Range);
Description
Description
Output the range to an ostream. Elements are outputed in a sequence without separators.
Function template make_iterator_range
Function template make_iterator_range -- iterator_range construct helper
boost::algorithm::make_iterator_range
template
<typename IteratorT> iterator_range< IteratorT > make_iterator_range(IteratorT Begin, IteratorT End);
Description
Description
Construct an iterator_range from a pair of iterators
Parameters
Begin
A begin iterator
End
An end iterator
Returns
iterator_range object
Function template make_iterator_range
Function template make_iterator_range -- iterator_range construct helper
boost::algorithm::make_iterator_range
template
<typename IteratorT> iterator_range< IteratorT > make_iterator_range(const std::pair< IteratorT, IteratorT > & Pair);
Description
Description
Construct an iterator_range from a std::pair<> containing the begin and end iterators.
Parameters
Pair
A std::pair<> with begin and end iterators
Returns
iterator_range
object
Function template copy_iterator_range
Function template copy_iterator_range -- copy a range into a sequence
boost::algorithm::copy_iterator_range
template
<typename SeqT, typename IteratorT> SeqT copy_iterator_range(const iterator_range< IteratorT > & Range);
Description
Description
Construct a new sequence of the specified type from the elements in the given range
Parameters
Range
An input range
Returns
New sequence
Function template transform_iterator_range
Function template transform_iterator_range -- transform a range into a sequence
boost::algorithm::transform_iterator_range
template
<typename SeqT, typename IteratorT, typename FuncT> SeqT transform_iterator_range(const iterator_range< IteratorT > & Range, FuncT Func);
Description
Description
Create a new sequence from the elements in the range, transformed by a function
Parameters
Func
Transformation function
Range
An input range
Returns
New sequence
Header <boost/algorithm/string/predicate.hpp>
Defines string-related predicates. The predicates determine whether a substring is contained in the input string under various conditions: a string starts with the substring, ends with the substring, simply contains the substring or if both strings are equal. Additionaly the algorithm all() checks all elements of a container to satisfy a condition.
All predicates provide the strong exception guarantee.
namespace
boost { namespace algorithm { template<typename Collection1T, typename Collection2T, typename PredicateT> bool starts_with(const Collection1T &, const Collection2T &, PredicateT); template<typename Collection1T, typename Collection2T> bool starts_with(const Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> bool istarts_with(const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename Collection1T, typename Collection2T, typename PredicateT> bool ends_with(const Collection1T &, const Collection2T &, PredicateT); template<typename Collection1T, typename Collection2T> bool ends_with(const Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> bool iends_with(const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename Collection1T, typename Collection2T, typename PredicateT> bool contains(const Collection1T &, const Collection2T &, PredicateT); template<typename Collection1T, typename Collection2T> bool contains(const Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> bool icontains(const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename Collection1T, typename Collection2T, typename PredicateT> bool equals(const Collection1T &, const Collection2T &, PredicateT); template<typename Collection1T, typename Collection2T> bool equals(const Collection1T &, const Collection2T &); template<typename Collection1T, typename Collection2T> bool iequals(const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename CollectionT, typename PredicateT> bool all(const CollectionT &, PredicateT); } }
Function starts_with
Function starts_with -- 'Starts with' predicate
boost::algorithm::starts_with
template
<typename Collection1T, typename Collection2T, typename PredicateT> bool starts_with(const Collection1T & Input, const Collection2T & Test, PredicateT Comp); template<typename Collection1T, typename Collection2T> bool starts_with(const Collection1T & Input, const Collection2T & Test);
Description
Description
This predicate holds when the test collection is a prefix of the Input. In other words, if the input starts with the test. When the optional predicate is specified, it is used for character-wise comparison.
Parameters
Comp
An element comparison predicate
Input
An input sequence
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function template istarts_with
Function template istarts_with -- 'Starts with' predicate ( case insensitive )
boost::algorithm::istarts_with
template
<typename Collection1T, typename Collection2T> bool istarts_with(const Collection1T & Input, const Collection2T & Test, const std::locale & Loc = std::locale());
Description
Description
This predicate holds when the test container is a prefix of the Input. In other words, if the input starts with the test. Elements are compared case insensitively.
Parameters
Input
An input sequence
Loc
A locale used for case insensitive comparison
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function ends_with
Function ends_with -- 'Ends with' predicate
boost::algorithm::ends_with
template
<typename Collection1T, typename Collection2T, typename PredicateT> bool ends_with(const Collection1T & Input, const Collection2T & Test, PredicateT Comp); template<typename Collection1T, typename Collection2T> bool ends_with(const Collection1T & Input, const Collection2T & Test);
Description
Description
This predicate holds when the test container is a suffix of the Input. In other words, if the input ends with the test. When the optional predicate is specified, it is used for character-wise comparison.
Parameters
Comp
An element comparison predicate
Input
An input sequence
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function template iends_with
Function template iends_with -- 'Ends with' predicate ( case insensitive )
boost::algorithm::iends_with
template
<typename Collection1T, typename Collection2T> bool iends_with(const Collection1T & Input, const Collection2T & Test, const std::locale & Loc = std::locale());
Description
Description
This predicate holds when the test container is a suffix of the Input. In other words, if the input ends with the test. Elements are compared case insensitively.
Parameters
Input
An input sequence
Loc
A locale used for case insensitive comparison
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function contains
Function contains -- 'Contains' predicate
boost::algorithm::contains
template
<typename Collection1T, typename Collection2T, typename PredicateT> bool contains(const Collection1T & Input, const Collection2T & Test, PredicateT Comp); template<typename Collection1T, typename Collection2T> bool contains(const Collection1T & Input, const Collection2T & Test);
Description
Description
This predicate holds when the test container is contained in the Input. When the optional predicate is specified, it is used for character-wise comparison.
Parameters
Comp
An element comparison predicate
Input
An input sequence
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function template icontains
Function template icontains -- 'Contains' predicate ( case insensitive )
boost::algorithm::icontains
template
<typename Collection1T, typename Collection2T> bool icontains(const Collection1T & Input, const Collection2T & Test, const std::locale & Loc = std::locale());
Description
Description
This predicate holds when the test container is contained in the Input. Elements are compared case insensitively.
Parameters
Input
An input sequence
Loc
A locale used for case insensitive comparison
Test
A test sequence
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Function equals
Function equals -- 'Equals' predicate
boost::algorithm::equals
template
<typename Collection1T, typename Collection2T, typename PredicateT> bool equals(const Collection1T & Input, const Collection2T & Test, PredicateT Comp); template<typename Collection1T, typename Collection2T> bool equals(const Collection1T & Input, const Collection2T & Test);
Description
Description
This predicate holds when the test container is equal to the input container i.e. all elements in both containers are same. When the optional predicate is specified, it is used for character-wise comparison.
Parameters
Comp
An element comparison predicate
Input
An input sequence
Test
A test sequence
Returns
The result of the test
Notes
This is a two-way version of std::equal algorithm
This function provides the strong exception-safety guarantee
Function template iequals
Function template iequals -- 'Equals' predicate ( casa insensitive )
boost::algorithm::iequals
template
<typename Collection1T, typename Collection2T> bool iequals(const Collection1T & Input, const Collection2T & Test, const std::locale & Loc = std::locale());
Description
Description
This predicate holds when the test container is equal to the input container i.e. all elements in both containers are same. Elements are compared case insensitively.
Parameters
Input
An input sequence
Loc
A locale used for case insensitive comparison
Test
A test sequence
Returns
The result of the test
Notes
This is a two-way version of std::equal algorithm
This function provides the strong exception-safety guarantee
Function template all
Function template all -- 'All' predicate
boost::algorithm::all
template
<typename CollectionT, typename PredicateT> bool all(const CollectionT & Input, PredicateT Pred);
Description
Description
This predicate holds it all its elements satisfy a given condition, represented by the predicate.
Parameters
Input
An input sequence
Pred
A predicate
Returns
The result of the test
Notes
This function provides the strong exception-safety guarantee
Header <boost/algorithm/string/regex.hpp>
Defines regex variants of the algorithms.
namespace
boost { namespace algorithm { template<typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> iterator_range< typename result_iterator_of< CollectionT >::type > find_regex(CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> OutputIteratorT replace_regex_copy(OutputIteratorT, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> SequenceT replace_regex_copy(const SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> void replace_regex(SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> OutputIteratorT replace_all_regex_copy(OutputIteratorT, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> SequenceT replace_all_regex_copy(const SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> void replace_all_regex(SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, match_flag_type = match_default|format_default); template<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> OutputIteratorT erase_regex_copy(OutputIteratorT, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceT erase_regex_copy(const SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> void erase_regex(SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> OutputIteratorT erase_all_regex_copy(OutputIteratorT, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceT erase_all_regex_copy(const SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> void erase_all_regex(SequenceT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceSequenceT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceSequenceT & find_all_regex(SequenceSequenceT &, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename SequenceSequenceT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceSequenceT & split_regex(SequenceSequenceT &, const CollectionT &, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); } }
Function template find_regex
Function template find_regex -- Find regex algorithm.
boost::algorithm::find_regex
template
<typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> iterator_range< typename result_iterator_of< CollectionT >::type > find_regex(CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Search for a substring matching the given regex in the input.
Parameters
Flags
Regex options
Input
A container which will be searched.
Rx
A regular expression
Returns
An iterator_range delimiting the match. Returned iterator is either InputContainerT::iterator or InputContainerT::const_iterator , depending on the constness of the input parameter.
Notes
This function provides the strong exception-safety guarantee
Function replace_regex_copy
Function replace_regex_copy -- Replace regex algorithm.
boost::algorithm::replace_regex_copy
template
<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> OutputIteratorT replace_regex_copy(OutputIteratorT Output, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> SequenceT replace_regex_copy(const SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default);
Description
Description
Search for a substring matching given regex and format it with the specified format. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Flags
Regex options
Format
Regex format definition
Input
An input string
Output
An output iterator to which the result will be copied
Rx
A regular expression
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_regex
Function template replace_regex -- Replace regex algorithm.
boost::algorithm::replace_regex
template
<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> void replace_regex(SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default);
Description
Description
Search for a substring matching given regex and format it with the specified format. The input string is modified in-place.
Parameters
Flags
Regex options
Format
Regex format definition
Input
An input string
Rx
A regular expression
Function replace_all_regex_copy
Function replace_all_regex_copy -- Replace all regex algorithm.
boost::algorithm::replace_all_regex_copy
template
<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> OutputIteratorT replace_all_regex_copy(OutputIteratorT Output, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> SequenceT replace_all_regex_copy(const SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default);
Description
Description
Format all substrings, matching given regex, with the specified format. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Flags
Regex options
Format
Regex format definition
Input
An input string
Output
An output iterator to which the result will be copied
Rx
A regular expression
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_all_regex
Function template replace_all_regex -- Replace all regex algorithm.
boost::algorithm::replace_all_regex
template
<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT, typename FormatStringTraitsT, typename FormatStringAllocatorT> void replace_all_regex(SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, match_flag_type Flags = match_default|format_default);
Description
Description
Format all substrings, matching given regex, with the specified format. The input string is modified in-place.
Parameters
Flags
Regex options
Format
Regex format definition
Input
An input string
Rx
A regular expression
Function erase_regex_copy
Function erase_regex_copy -- Erase regex algorithm.
boost::algorithm::erase_regex_copy
template
<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> OutputIteratorT erase_regex_copy(OutputIteratorT Output, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceT erase_regex_copy(const SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Remove a substring matching given regex from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Flags
Regex options
Input
An input string
Output
An output iterator to which the result will be copied
Rx
A regular expression
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_regex
Function template erase_regex -- Erase regex algorithm.
boost::algorithm::erase_regex
template
<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> void erase_regex(SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Remove a substring matching given regex from the input. The input string is modified in-place.
Parameters
Flags
Regex options
Input
An input string
Rx
A regular expression
Function erase_all_regex_copy
Function erase_all_regex_copy -- Erase all regex algorithm.
boost::algorithm::erase_all_regex_copy
template
<typename OutputIteratorT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> OutputIteratorT erase_all_regex_copy(OutputIteratorT Output, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default); template<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceT erase_all_regex_copy(const SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Erase all substrings, matching given regex, from the input. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Flags
Regex options
Input
An input string
Output
An output iterator to which the result will be copied
Rx
A regular expression
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template erase_all_regex
Function template erase_all_regex -- Erase all regex algorithm.
boost::algorithm::erase_all_regex
template
<typename SequenceT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> void erase_all_regex(SequenceT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Erase all substrings, matching given regex, from the input. The input string is modified in-place.
Parameters
Flags
Regex options
Input
An input string
Rx
A regular expression
Function template find_all_regex
Function template find_all_regex -- Find all regex algorithm.
boost::algorithm::find_all_regex
template
<typename SequenceSequenceT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceSequenceT & find_all_regex(SequenceSequenceT & Result, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
This algorithm finds all substrings matching the give regex in the input.
Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
Parameters
Flags
Regex options
Input
A container which will be searched.
Result
A container that can hold copies of references to the substrings.
Rx
A regular expression
Returns
A reference to the result
Notes
Prior content of the result will be overwritten.
This function provides the strong exception-safety guarantee
Function template split_regex
Function template split_regex -- Split regex algorithm.
boost::algorithm::split_regex
template
<typename SequenceSequenceT, typename CollectionT, typename CharT, typename RegexTraitsT, typename RegexAllocatorT> SequenceSequenceT & split_regex(SequenceSequenceT & Result, const CollectionT & Input, const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type Flags = match_default);
Description
Description
Tokenize expression. This function is equivalent to C strtok. Input sequence is split into tokens, separated by separators. Separator is an every match of the given regex. Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
Parameters
Flags
Regex options
Input
A container which will be searched.
Result
A container that can hold copies of references to the substrings.
Rx
A regular expression
Returns
A reference to the result
Notes
Prior content of the result will be overwritten.
This function provides the strong exception-safety guarantee
Header <boost/algorithm/string/regex_find_format.hpp>
Defines the regex_finder and regex_formatter generators. These two functors are designed to work together. regex_formatter uses additional information about a match contained in the regex_finder search result.
namespace
boost { namespace algorithm { template<typename CharT, typename RegexTraitsT, typename RegexAllocatorT> unspecified regex_finder(const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > &, match_flag_type = match_default); template<typename CharT, typename TraitsT, typename AllocT> unspecified regex_formatter(const std::basic_string< CharT, TraitsT, AllocT > &, match_flag_type = format_default); } }
Function template regex_finder
Function template regex_finder -- "Regex" finder
boost::algorithm::regex_finder
template
<typename CharT, typename RegexTraitsT, typename RegexAllocatorT> unspecified regex_finder(const reg_expression< CharT, RegexTraitsT, RegexAllocatorT > & Rx, match_flag_type MatchFlags = match_default);
Description
Description
Construct the regex_finder . Finder uses the regex engine to search for a match. Result is given in regex_search_result . This is an extension of the iterator_range. In addition it containes match results from the regex_search algorithm.
Parameters
MatchFlags
Regex search options
Rx
A regular expression
Returns
An instance of the regex_finder object
Function template regex_formatter
Function template regex_formatter -- Regex formatter.
boost::algorithm::regex_formatter
template
<typename CharT, typename TraitsT, typename AllocT> unspecified regex_formatter(const std::basic_string< CharT, TraitsT, AllocT > & Format, match_flag_type Flags = format_default);
Description
Description
Construct the regex_formatter . Regex formatter uses the regex engine to format a match found by the regex_finder . This formatted it designed to closely cooperate with regex_finder .
Parameters
Flags
Format flags
Format
Regex format definition
Returns
An instance of the regex_formatter functor
Header <boost/algorithm/string/replace.hpp>
Defines various replace algorithms. Each algorithm replaces part(s) of the input according to set of searching and replace criteria.
namespace
boost { namespace algorithm { template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_range_copy(OutputIteratorT, const Collection1T &, const iterator_range< typename const_iterator_of< Collection1T >::type > &, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT replace_range_copy(const SequenceT &, const iterator_range< typename const_iterator_of< SequenceT >::type > &, const CollectionT &); template<typename SequenceT, typename CollectionT> void replace_range(SequenceT &, const iterator_range< typename iterator_of< SequenceT >::type > &, const CollectionT &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_first_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_first_copy(const SequenceT &, const Collection1T &, const Collection2T &); template<typename SequenceT, typename Collection1T, typename Collection2T> void replace_first(SequenceT &, const Collection1T &, const Collection2T &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_first_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection2T, typename Collection1T> SequenceT ireplace_first_copy(const SequenceT &, const Collection2T &, const Collection1T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_first(SequenceT &, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_last_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_last_copy(const SequenceT &, const Collection1T &, const Collection2T &); template<typename SequenceT, typename Collection1T, typename Collection2T> void replace_last(SequenceT &, const Collection1T &, const Collection2T &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_last_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_last_copy(const SequenceT &, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_last(SequenceT &, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_nth_copy(OutputIteratorT, const Collection1T &, const Collection2T &, unsigned int, const Collection3T &); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_nth_copy(const SequenceT &, const Collection1T &, unsigned int, const Collection2T &); template<typename SequenceT, typename Collection1T, typename Collection2T> void replace_nth(SequenceT &, const Collection1T &, unsigned int, const Collection2T &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_nth_copy(OutputIteratorT, const Collection1T &, const Collection2T &, unsigned int, const Collection3T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_nth_copy(const SequenceT &, const Collection1T &, unsigned int, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_nth(SequenceT &, const Collection1T &, unsigned int, const Collection2T &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_all_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_all_copy(const SequenceT &, const Collection1T &, const Collection2T &); template<typename SequenceT, typename Collection1T, typename Collection2T> void replace_all(SequenceT &, const Collection1T &, const Collection2T &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_all_copy(OutputIteratorT, const Collection1T &, const Collection2T &, const Collection3T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_all_copy(const SequenceT &, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_all(SequenceT &, const Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_head_copy(OutputIteratorT, const Collection1T &, unsigned int, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT replace_head_copy(const SequenceT &, unsigned int, const CollectionT &); template<typename SequenceT, typename CollectionT> void replace_head(SequenceT &, unsigned int, const CollectionT &); template<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_tail_copy(OutputIteratorT, const Collection1T &, unsigned int, const Collection2T &); template<typename SequenceT, typename CollectionT> SequenceT replace_tail_copy(const SequenceT &, unsigned int, const CollectionT &); template<typename SequenceT, typename CollectionT> void replace_tail(SequenceT &, unsigned int, const CollectionT &); } }
Function replace_range_copy
Function replace_range_copy -- Replace range algorithm.
boost::algorithm::replace_range_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_range_copy(OutputIteratorT Output, const Collection1T & Input, const iterator_range< typename const_iterator_of< Collection1T >::type > & SearchRange, const Collection2T & Format); template<typename SequenceT, typename CollectionT> SequenceT replace_range_copy(const SequenceT & Input, const iterator_range< typename const_iterator_of< SequenceT >::type > & SearchRange, const CollectionT & Format);
Description
Description
Replace the given range in the input string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
Output
An output iterator to which the result will be copied
SearchRange
A range in the input to be substituted
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_range
Function template replace_range -- Replace range algorithm.
boost::algorithm::replace_range
template
<typename SequenceT, typename CollectionT> void replace_range(SequenceT & Input, const iterator_range< typename iterator_of< SequenceT >::type > & SearchRange, const CollectionT & Format);
Description
Description
Replace the given range in the input string. The input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
SearchRange
A range in the input to be substituted
Function replace_first_copy
Function replace_first_copy -- Replace first algorithm.
boost::algorithm::replace_first_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_first_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_first_copy(const SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
Replace the first match of the search substring in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_first
Function template replace_first -- Replace first algorithm.
boost::algorithm::replace_first
template
<typename SequenceT, typename Collection1T, typename Collection2T> void replace_first(SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
replace the first match of the search substring in the input with the format string. The input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
Search
A substring to be searched for
Function ireplace_first_copy
Function ireplace_first_copy -- Replace first algorithm ( case insensitive ).
boost::algorithm::ireplace_first_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_first_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format, const std::locale & Loc = std::locale()); template<typename SequenceT, typename Collection2T, typename Collection1T> SequenceT ireplace_first_copy(const SequenceT & Input, const Collection2T & Search, const Collection1T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace the first match of the search substring in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ireplace_first
Function template ireplace_first -- Replace first algorithm ( case insensitive ).
boost::algorithm::ireplace_first
template
<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_first(SequenceT & Input, const Collection1T & Search, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace the first match of the search substring in the input with the format string. Input sequence is modified in-place. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for
Function replace_last_copy
Function replace_last_copy -- Replace last algorithm.
boost::algorithm::replace_last_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_last_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_last_copy(const SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
Replace the last match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_last
Function template replace_last -- Replace last algorithm.
boost::algorithm::replace_last
template
<typename SequenceT, typename Collection1T, typename Collection2T> void replace_last(SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
Replace the last match of the search string in the input with the format string. Input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
Search
A substring to be searched for
Function ireplace_last_copy
Function ireplace_last_copy -- Replace last algorithm ( case insensitive ).
boost::algorithm::ireplace_last_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_last_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format, const std::locale & Loc = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_last_copy(const SequenceT & Input, const Collection1T & Search, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace the last match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ireplace_last
Function template ireplace_last -- Replace last algorithm ( case insensitive ).
boost::algorithm::ireplace_last
template
<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_last(SequenceT & Input, const Collection1T & Search, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace the last match of the search string in the input with the format string.The input sequence is modified in-place. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for
Returns
A reference to the modified input
Function replace_nth_copy
Function replace_nth_copy -- Replace nth algorithm.
boost::algorithm::replace_nth_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_nth_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, unsigned int Nth, const Collection3T & Format); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_nth_copy(const SequenceT & Input, const Collection1T & Search, unsigned int Nth, const Collection2T & Format);
Description
Description
Replace an Nth (zero-indexed) match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
Nth
An index of the match to be replaced. The index is 0-based.
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_nth
Function template replace_nth -- Replace nth algorithm.
boost::algorithm::replace_nth
template
<typename SequenceT, typename Collection1T, typename Collection2T> void replace_nth(SequenceT & Input, const Collection1T & Search, unsigned int Nth, const Collection2T & Format);
Description
Description
Replace an Nth (zero-indexed) match of the search string in the input with the format string. Input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
Nth
An index of the match to be replaced. The index is 0-based.
Search
A substring to be searched for
Function ireplace_nth_copy
Function ireplace_nth_copy -- Replace nth algorithm ( case insensitive ).
boost::algorithm::ireplace_nth_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_nth_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, unsigned int Nth, const Collection3T & Format, const std::locale & Loc = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_nth_copy(const SequenceT & Input, const Collection1T & Search, unsigned int Nth, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace an Nth (zero-indexed) match of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Nth
An index of the match to be replaced. The index is 0-based.
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ireplace_nth
Function template ireplace_nth -- Replace nth algorithm ( case insensitive ).
boost::algorithm::ireplace_nth
template
<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_nth(SequenceT & Input, const Collection1T & Search, unsigned int Nth, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace an Nth (zero-indexed) match of the search string in the input with the format string. Input sequence is modified in-place. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Nth
An index of the match to be replaced. The index is 0-based.
Search
A substring to be searched for
Function replace_all_copy
Function replace_all_copy -- Replace all algorithm.
boost::algorithm::replace_all_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT replace_all_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT replace_all_copy(const SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
Replace all occurrences of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_all
Function template replace_all -- Replace all algorithm.
boost::algorithm::replace_all
template
<typename SequenceT, typename Collection1T, typename Collection2T> void replace_all(SequenceT & Input, const Collection1T & Search, const Collection2T & Format);
Description
Description
Replace all occurrences of the search string in the input with the format string. The input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
Search
A substring to be searched for
Returns
A reference to the modified input
Function ireplace_all_copy
Function ireplace_all_copy -- Replace all algorithm ( case insensitive ).
boost::algorithm::ireplace_all_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T, typename Collection3T> OutputIteratorT ireplace_all_copy(OutputIteratorT Output, const Collection1T & Input, const Collection2T & Search, const Collection3T & Format, const std::locale & Loc = std::locale()); template<typename SequenceT, typename Collection1T, typename Collection2T> SequenceT ireplace_all_copy(const SequenceT & Input, const Collection1T & Search, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace all occurrences of the search string in the input with the format string. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Output
An output iterator to which the result will be copied
Search
A substring to be searched for
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template ireplace_all
Function template ireplace_all -- Replace all algorithm ( case insensitive ).
boost::algorithm::ireplace_all
template
<typename SequenceT, typename Collection1T, typename Collection2T> void ireplace_all(SequenceT & Input, const Collection1T & Search, const Collection2T & Format, const std::locale & Loc = std::locale());
Description
Description
Replace all occurrences of the search string in the input with the format string.The input sequence is modified in-place. Searching is case insensitive.
Parameters
Format
A substitute string
Input
An input string
Loc
A locale used for case insensitive comparison
Search
A substring to be searched for
Function replace_head_copy
Function replace_head_copy -- Replace head algorithm.
boost::algorithm::replace_head_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_head_copy(OutputIteratorT Output, const Collection1T & Input, unsigned int N, const Collection2T & Format); template<typename SequenceT, typename CollectionT> SequenceT replace_head_copy(const SequenceT & Input, unsigned int N, const CollectionT & Format);
Description
Description
Replace the head of the input with the given format string. The head is a prefix of a string of given size. If the sequence is shorter then required, whole string if considered to be the head. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
N
Length of the head
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_head
Function template replace_head -- Replace head algorithm.
boost::algorithm::replace_head
template
<typename SequenceT, typename CollectionT> void replace_head(SequenceT & Input, unsigned int N, const CollectionT & Format);
Description
Description
Replace the head of the input with the given format string. The head is a prefix of a string of given size. If the sequence is shorter then required, the whole string is considered to be the head. The input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
N
Length of the head
Function replace_tail_copy
Function replace_tail_copy -- Replace tail algorithm.
boost::algorithm::replace_tail_copy
template
<typename OutputIteratorT, typename Collection1T, typename Collection2T> OutputIteratorT replace_tail_copy(OutputIteratorT Output, const Collection1T & Input, unsigned int N, const Collection2T & Format); template<typename SequenceT, typename CollectionT> SequenceT replace_tail_copy(const SequenceT & Input, unsigned int N, const CollectionT & Format);
Description
Description
Replace the tail of the input with the given format string. The tail is a suffix of a string of given size. If the sequence is shorter then required, whole string is considered to be the tail. The result is a modified copy of the input. It is returned as a sequence or copied to the output iterator.
Parameters
Format
A substitute string
Input
An input string
N
Length of the tail
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a modified copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template replace_tail
Function template replace_tail -- Replace tail algorithm.
boost::algorithm::replace_tail
template
<typename SequenceT, typename CollectionT> void replace_tail(SequenceT & Input, unsigned int N, const CollectionT & Format);
Description
Description
Replace the tail of the input with the given format sequence. The tail is a suffix of a string of given size. If the sequence is shorter then required, the whole string is considered to be the tail. The input sequence is modified in-place.
Parameters
Format
A substitute string
Input
An input string
N
Length of the tail
Header <boost/algorithm/string/sequence_traits.hpp>
Traits defined in this header are used by various algorithms to achieve better performance for specific containers. Traits provide fail-safe defaults. If a container supports some of these features, it is possible to specialize the specific trait for this container. For lacking compilers, it is possible of define an override for a specific tester function.
Due to a language restriction, it is not currently possible to define specializations for stl containers without including the corresponding header. To decrease the overhead needed by this inclusion, user can selectively include a specialization header for a specific container. They are located in boost/algorithm/string/stl directory. Alternatively she can include boost/algorithm/string/std_collection_traits.hpp header which contains specializations for all stl containers.
namespace
boost { namespace algorithm { template<typename T> class has_native_replace; template<typename T> class has_stable_iterators; template<typename T> class has_const_time_insert; template<typename T> class has_const_time_erase; } }
Class template has_native_replace
Class template has_native_replace -- Native replace trait.
boost::algorithm::has_native_replace
template
<typename T> class has_native_replace { public: // types typedef mpl::bool_< value > type;

// public member functions
BOOST_STATIC_CONSTANT
(bool, value = false) ; };
Description
Description
This trait specifies that the sequence has std::string like replace method
has_native_replace public member functions
has_native_replace
public member functions
1.
BOOST_STATIC_CONSTANT(bool , value = false) ;
Class template has_stable_iterators
Class template has_stable_iterators -- Stable iterators trait.
boost::algorithm::has_stable_iterators
template
<typename T> class has_stable_iterators { public: // types typedef mpl::bool_< value > type;

// public member functions
BOOST_STATIC_CONSTANT
(bool, value = false) ; };
Description
Description
This trait specifies that the sequence has stable iterators. It means that operations like insert/erase/replace do not invalidate iterators.
has_stable_iterators public member functions
has_stable_iterators
public member functions
1.
BOOST_STATIC_CONSTANT(bool , value = false) ;
Class template has_const_time_insert
Class template has_const_time_insert -- Const time insert trait.
boost::algorithm::has_const_time_insert
template
<typename T> class has_const_time_insert { public: // types typedef mpl::bool_< value > type;

// public member functions
BOOST_STATIC_CONSTANT
(bool, value = false) ; };
Description
Description
This trait specifies that the sequence's insert method has constant time complexity.
has_const_time_insert public member functions
has_const_time_insert
public member functions
1.
BOOST_STATIC_CONSTANT(bool , value = false) ;
Class template has_const_time_erase
Class template has_const_time_erase -- Const time erase trait.
boost::algorithm::has_const_time_erase
template
<typename T> class has_const_time_erase { public: // types typedef mpl::bool_< value > type;

// public member functions
BOOST_STATIC_CONSTANT
(bool, value = false) ; };
Description
Description
This trait specifies that the sequence's erase method has constant time complexity.
has_const_time_erase public member functions
has_const_time_erase
public member functions
1.
BOOST_STATIC_CONSTANT(bool , value = false) ;
Header <boost/algorithm/string/split.hpp>
Defines basic split algorithms. Split algorithms can be used to divide a string into several parts according to given criteria.
Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
namespace
boost { namespace algorithm { template<typename SequenceSequenceT, typename Collection1T, typename Collection2T> SequenceSequenceT & find_all(SequenceSequenceT &, Collection1T &, const Collection2T &); template<typename SequenceSequenceT, typename Collection1T, typename Collection2T> SequenceSequenceT & ifind_all(SequenceSequenceT &, Collection1T &, const Collection2T &, const std::locale & = std::locale()); template<typename SequenceSequenceT, typename CollectionT, typename PredicateT> SequenceSequenceT & split(SequenceSequenceT &, CollectionT &, PredicateT, token_compress_mode_type = token_compress_off); } }
Function template find_all
Function template find_all -- Find all algorithm.
boost::algorithm::find_all
template
<typename SequenceSequenceT, typename Collection1T, typename Collection2T> SequenceSequenceT & find_all(SequenceSequenceT & Result, Collection1T & Input, const Collection2T & Search);
Description
Description
This algorithm finds all occurrences of the search string in the input.
Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
Parameters
Input
A container which will be searched.
Result
A container that can hold copies of references to the substrings
Search
A substring to be searched for.
Returns
A reference the result
Notes
Prior content of the result will be overwritten.
This function provides the strong exception-safety guarantee
Function template ifind_all
Function template ifind_all -- Find all algorithm ( case insensitive ).
boost::algorithm::ifind_all
template
<typename SequenceSequenceT, typename Collection1T, typename Collection2T> SequenceSequenceT & ifind_all(SequenceSequenceT & Result, Collection1T & Input, const Collection2T & Search, const std::locale & Loc = std::locale());
Description
Description
This algorithm finds all occurrences of the search string in the input. Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
Searching is case insensitive.
Parameters
Input
A container which will be searched.
Loc
A locale used for case insensitive comparison
Result
A container that can hold copies of references to the substrings
Search
A substring to be searched for.
Returns
A reference the result
Notes
Prior content of the result will be overwritten.
This function provides the strong exception-safety guarantee
Function template split
Function template split -- Split algorithm.
boost::algorithm::split
template
<typename SequenceSequenceT, typename CollectionT, typename PredicateT> SequenceSequenceT & split(SequenceSequenceT & Result, CollectionT & Input, PredicateT Pred, token_compress_mode_type eCompress = token_compress_off);
Description
Description
Tokenize expression. This function is equivalent to C strtok. Input sequence is split into tokens, separated by separators. Separators are given by means of the predicate.
Each part is copied and added as a new element to the output container. Thus the result container must be able to hold copies of the matches (in a compatible structure like std::string) or a reference to it (e.g. using the iterator range class). Examples of such a container are std::vector<std::string> or std::list<boost::iterator_range<std::string::iterator>>
Parameters
Input
A container which will be searched.
Pred
A predicate to identify separators. This predicate is supposed to return true if a given element is a separator.
Result
A container that can hold copies of references to the substrings
eCompress
If eCompress argument is set to token_compress_on, adjacent separators are merged together. Otherwise, every two separators delimit a token.
Returns
A reference the result
Notes
Prior content of the result will be overwritten.
This function provides the strong exception-safety guarantee
Header <boost/algorithm/string/std_containers_traits.hpp>
This file includes sequence traits for stl containers.
Header <boost/algorithm/string.hpp>
Cumulative include for string_algo library
Header <boost/algorithm/string_regex.hpp>
Cumulative include for string_algo library. In addtion to string.hpp contains also regex-related stuff.
Header <boost/algorithm/string/trim.hpp>
Defines trim algorithms. Trim algorithms are used to remove trailing and leading spaces from a sequence (string). Space is recognized using given locales.
Parametric (_if ) variants use a predicate (functor) to select which characters are to be trimmed.. Functions take a selection predicate as a parameter, which is used to determine whether a character is a space. Common predicates are provided in classification.hpp header.
namespace
boost { namespace algorithm { template<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_left_copy_if(OutputIteratorT, const CollectionT &, PredicateT); template<typename SequenceT, typename PredicateT> SequenceT trim_left_copy_if(const SequenceT &, PredicateT); template<typename SequenceT> SequenceT trim_left_copy(const SequenceT &, const std::locale & = std::locale()); template<typename SequenceT, typename PredicateT> void trim_left_if(SequenceT &, PredicateT); template<typename SequenceT> void trim_left(SequenceT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_right_copy_if(OutputIteratorT, const CollectionT &, PredicateT); template<typename SequenceT, typename PredicateT> SequenceT trim_right_copy_if(const SequenceT &, PredicateT); template<typename SequenceT> SequenceT trim_right_copy(const SequenceT &, const std::locale & = std::locale()); template<typename SequenceT, typename PredicateT> void trim_right_if(SequenceT &, PredicateT); template<typename SequenceT> void trim_right(SequenceT &, const std::locale & = std::locale()); template<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_copy_if(OutputIteratorT, const CollectionT &, PredicateT); template<typename SequenceT, typename PredicateT> SequenceT trim_copy_if(const SequenceT &, PredicateT); template<typename SequenceT> SequenceT trim_copy(const SequenceT &, const std::locale & = std::locale()); template<typename SequenceT, typename PredicateT> void trim_if(SequenceT &, PredicateT); template<typename SequenceT> void trim(SequenceT &, const std::locale & = std::locale()); } }
Function trim_left_copy_if
Function trim_left_copy_if -- Left trim - parametric.
boost::algorithm::trim_left_copy_if
template
<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_left_copy_if(OutputIteratorT Output, const CollectionT & Input, PredicateT IsSpace); template<typename SequenceT, typename PredicateT> SequenceT trim_left_copy_if(const SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all leading spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The result is a trimmed copy of the input. It is returned as a sequence or copied to the output iterator
Parameters
Input
An input collection
IsSpace
An unary predicate identifying spaces
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template trim_left_copy
Function template trim_left_copy -- Left trim - parametric.
boost::algorithm::trim_left_copy
template
<typename SequenceT> SequenceT trim_left_copy(const SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all leading spaces from the input. The result is a trimmed copy of the input.
Parameters
Input
An input sequence
Loc
a locale used for 'space' classification
Returns
A trimmed copy of the input
Notes
This function provides the strong exception-safety guarantee
Function template trim_left_if
Function template trim_left_if -- Left trim.
boost::algorithm::trim_left_if
template
<typename SequenceT, typename PredicateT> void trim_left_if(SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all leading spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The input sequence is modified in-place.
Parameters
Input
An input sequence
IsSpace
An unary predicate identifying spaces
Function template trim_left
Function template trim_left -- Left trim.
boost::algorithm::trim_left
template
<typename SequenceT> void trim_left(SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all leading spaces from the input. The Input sequence is modified in-place.
Parameters
Input
An input sequence
Loc
A locale used for 'space' classification
Function trim_right_copy_if
Function trim_right_copy_if -- Right trim - parametric.
boost::algorithm::trim_right_copy_if
template
<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_right_copy_if(OutputIteratorT Output, const CollectionT & Input, PredicateT IsSpace); template<typename SequenceT, typename PredicateT> SequenceT trim_right_copy_if(const SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all trailing spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The result is a trimmed copy of the input. It is returned as a sequence or copied to the output iterator
Parameters
Input
An input collection
IsSpace
An unary predicate identifying spaces
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template trim_right_copy
Function template trim_right_copy -- Right trim.
boost::algorithm::trim_right_copy
template
<typename SequenceT> SequenceT trim_right_copy(const SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all trailing spaces from the input. The result is a trimmed copy of the input
Parameters
Input
An input sequence
Loc
A locale used for 'space' classification
Returns
A trimmed copy of the input
Notes
This function provides the strong exception-safety guarantee
Function template trim_right_if
Function template trim_right_if -- Right trim - parametric.
boost::algorithm::trim_right_if
template
<typename SequenceT, typename PredicateT> void trim_right_if(SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all trailing spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The input sequence is modified in-place.
Parameters
Input
An input sequence
IsSpace
An unary predicate identifying spaces
Function template trim_right
Function template trim_right -- Right trim.
boost::algorithm::trim_right
template
<typename SequenceT> void trim_right(SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all trailing spaces from the input. The input sequence is modified in-place.
Parameters
Input
An input sequence
Loc
A locale used for 'space' classification
Function trim_copy_if
Function trim_copy_if -- Trim - parametric.
boost::algorithm::trim_copy_if
template
<typename OutputIteratorT, typename CollectionT, typename PredicateT> OutputIteratorT trim_copy_if(OutputIteratorT Output, const CollectionT & Input, PredicateT IsSpace); template<typename SequenceT, typename PredicateT> SequenceT trim_copy_if(const SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all trailing and leading spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The result is a trimmed copy of the input. It is returned as a sequence or copied to the output iterator
Parameters
Input
An input collection
IsSpace
An unary predicate identifying spaces
Output
An output iterator to which the result will be copied
Returns
An output iterator pointing just after the last inserted character or a copy of the input
Notes
The second variant of this function provides the strong exception-safety guarantee
Function template trim_copy
Function template trim_copy -- Trim.
boost::algorithm::trim_copy
template
<typename SequenceT> SequenceT trim_copy(const SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all leading and trailing spaces from the input. The result is a trimmed copy of the input
Parameters
Input
An input sequence
Loc
A locale used for 'space' classification
Returns
A trimmed copy of the input
Notes
This function provides the strong exception-safety guarantee
Function template trim_if
Function template trim_if -- Trim.
boost::algorithm::trim_if
template
<typename SequenceT, typename PredicateT> void trim_if(SequenceT & Input, PredicateT IsSpace);
Description
Description
Remove all leading and trailing spaces from the input. The supplied predicate is used to determine which characters are considered spaces. The input sequence is modified in-place.
Parameters
Input
An input sequence
IsSpace
An unary predicate identifying spaces
Function template trim
Function template trim -- Trim.
boost::algorithm::trim
template
<typename SequenceT> void trim(SequenceT & Input, const std::locale & Loc = std::locale());
Description
Description
Remove all leading and trailing spaces from the input. The input sequence is modified in-place.
Parameters
Input
An input sequence
Loc
A locale used for 'space' classification
Rationale
Rationale
Locales
Locales have a very close relation to string processing. They contain information about the character sets and are used, for example, to change the case of characters and to classify the characters.
C++ allows to work with multiple different instances of locales at once. If an algorithm manipulates some data in a way that requires the usage of locales, there must be a way to specify them. However, one instance of locales is sufficient for most of the applications, and for a user it could be very tedious to specify which locales to use at every place where it is needed.
Fortunately, the C++ standard allows to specify the global locales (using static member function std:locale::global()). When instantiating an std::locale class without explicit information, the instance will be initialized with the global locale. This implies, that if an algorithm needs a locale, it should have an std::locale parameter defaulting to std::locale(). If a user needs to specify locales explicitly, she can do so. Otherwise the global locales are used.
Regular Expressions
Regular expressions are an essential part of text processing. For this reason, the library also provides regex variants of some algorithms. The library does not attempt to replace Boost.Regex; it merely wraps its functionality in a new interface. As a part of this library, regex algorithms integrate smoothly with other components, which brings additional value.
Environment
Environment
Build
The whole library is provided in headers. Regex variants of some algorithms, however, are dependent on the Boost.Regex library. All such algorithms are separated in boost/algorithm/string_regex.hpp. If this header is used, the application must be linked with the Boost.Regex library.
Examples
Examples showing the basic usage of the library can be found in the libs/algorithm/string/example directory. There is a separate file for the each part of the library. Please follow the boost build guidelines to build examples using the bjam. To successfully build regex examples the Boost.Regex library is required.
Tests
A full set of test cases for the library is located in the libs/algorithm/string/test directory. The test cases can be executed using the boost build system. For the tests of regular expression variants of algorithms, the Boost.Regex library is required.
Portability
The library has been successfully compiled and tested with the following compilers:

•
Microsoft Visual C++ 7.0
•
Microsoft Visual C++ 7.1
•
GCC 3.2
•
GCC 3.3.1

See Boost regression tables for additional info for a particular compiler.
There are known limitation on platforms not supporting partial template specialization. Library depends on correctly implemented std::iterator_traits class. If a standard library provided with compiler is broken, the String Algorithm Library cannot function properly. Usually it implies that primitive pointer iterators are not working with the library functions.
Credits
Credits
Acknowledgments
The author would like to thank everybody who gave suggestions and comments. Especially valuable were the contributions of Thorsten Ottosen, Jeff Garland and the other boost members who participated in the review process, namely David Abrahams, Daniel Frey, Beman Dawes, John Maddock, David B.Held, Pavel Vozenilek and many other.
Additional thanks go to Stefan Slapeta and Toon Knapen, who have been very resourceful in solving various portability issues.

Boost.Threads

Boost.Threads

Boost.Threads
William E. Kempf
Copyright © 2001-2003 William E. Kempf
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. William E. Kempf makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
Overview
Overview
Introduction
Boost.Threads
allows C++ programs to execute as multiple, asynchronous, independent threads-of-execution. Each thread has its own machine state including program instruction counter and registers. Programs which execute as multiple threads are called multithreaded programs to distinguish them from traditional single-threaded programs. The glossary gives a more complete description of the multithreading execution environment.
Multithreading provides several advantages: •Programs which would otherwise block waiting for some external event can continue to respond if the blocking operation is placed in a separate thread. Multithreading is usually an absolute requirement for these programs.•Well-designed multithreaded programs may execute faster than single-threaded programs, particularly on multiprocessor hardware. Note, however, that poorly-designed multithreaded programs are often slower than single-threaded programs.•Some program designs may be easier to formulate using a multithreaded approach. After all, the real world is asynchronous!
Dangers
General considerations
Beyond the errors which can occur in single-threaded programs, multithreaded programs are subject to additional errors: •Race conditions•Deadlock (sometimes called "deadly embrace")•Priority failures (priority inversion, infinite overtaking, starvation, etc.)
Every multithreaded program must be designed carefully to avoid these errors. These aren't rare or exotic failures - they are virtually guaranteed to occur unless multithreaded code is designed to avoid them. Priority failures are somewhat less common, but are nonetheless serious.
The Boost.Threads design attempts to minimize these errors, but they will still occur unless the programmer proactively designs to avoid them.
Note
Please also see the section called “Implementation Notes” for additional, implementation-specific considerations.
Testing and debugging considerations
Multithreaded programs are non-deterministic. In other words, the same program with the same input data may follow different execution paths each time it is invoked. That can make testing and debugging a nightmare: •Failures are often not repeatable.•Probe effect causes debuggers to produce very different results from non-debug uses.•Debuggers require special support to show thread state.•Tests on a single processor system may give no indication of serious errors which would appear on multiprocessor systems, and visa versa. Thus test cases should include a varying number of processors.•For programs which create a varying number of threads according to workload, tests which don't span the full range of possibilities may miss serious errors.
Getting a head start
Although it might appear that multithreaded programs are inherently unreliable, many reliable multithreaded programs do exist. Multithreading techniques are known which lead to reliable programs.
Design patterns for reliable multithreaded programs, including the important monitor pattern, are presented in Pattern-Oriented Software Architecture Volume 2 - Patterns for Concurrent and Networked Objects[SchmidtStalRohnertBuschmann]. Many important multithreading programming considerations (independent of threading library) are discussed in Programming with POSIX Threads[Butenhof97].
Doing some reading before attempting multithreaded designs will give you a head start toward reliable multithreaded programs.
C++ Standard Library usage in multithreaded programs
Runtime libraries
Warning:
Multithreaded programs such as those using Boost.Threads must link to thread-safe versions of all runtime libraries used by the program, including the runtime library for the C++ Standard Library. Failure to do so will cause race conditions to occur when multiple threads simultaneously execute runtime library functions for new, delete, or other language features which imply shared state.
Potentially non-thread-safe functions
Certain C++ Standard Library functions inherited from C are particular problems because they hold internal state between calls: •rand•strtok•asctime•ctime•gmtime•localtime
It is possible to write thread-safe implementations of these by using thread specific storage (see boost::thread_specific_ptr), and several C++ compiler vendors do just that. The technique is well-know and is explained in [Butenhof97].
But at least one vendor (HP-UX) does not provide thread-safe implementations of the above functions in their otherwise thread-safe runtime library. Instead they provide replacement functions with different names and arguments.
Recommendation:
For the most portable, yet thread-safe code, use Boost replacements for the problem functions. See the Boost Random Number Library and Boost Tokenizer Library.
Common guarantees for all Boost.Threads components
Exceptions
Boost.Threads
destructors never throw exceptions. Unless otherwise specified, other Boost.Threads functions that do not have an exception-specification may throw implementation-defined exceptions.
In particular, Boost.Threads reports failure to allocate storage by throwing an exception of type std::bad_alloc or a class derived from std::bad_alloc, failure to obtain thread resources other than memory by throwing an exception of type boost::thread_resource_error, and certain lock related failures by throwing an exception of type boost::lock_error.
Rationale:
Follows the C++ Standard Library practice of allowing all functions except destructors or other specified functions to throw exceptions on errors.
NonCopyable requirement
Boost.Threads
classes documented as meeting the NonCopyable requirement disallow copy construction and copy assignment. For the sake of exposition, the synopsis of such classes show private derivation from boost::noncopyable. Users should not depend on this derivation, however, as implementations are free to meet the NonCopyable requirement in other ways.
Design
Design
With client/server and three-tier architectures becoming common place in today's world, it's becoming increasingly important for programs to be able to handle parallel processing. Modern day operating systems usually provide some support for this through native thread APIs. Unfortunately, writing portable code that makes use of parallel processing in C++ is made very difficult by a lack of a standard interface for these native APIs. Further, these APIs are almost universally C APIs and fail to take advantage of C++'s strengths, or to address concepts unique to C++, such as exceptions.
The Boost.Threads library is an attempt to define a portable interface for writing parallel processes in C++.
Goals
The Boost.Threads library has several goals that should help to set it apart from other solutions. These goals are listed in order of precedence with full descriptions below. Portability Boost.Threads was designed to be highly portable. The goal is for the interface to be easily implemented on any platform that supports threads, and possibly even on platforms without native thread support.Safety Boost.Threads was designed to be as safe as possible. Writing thread-safe code is very difficult and successful libraries must strive to insulate the programmer from dangerous constructs as much as possible. This is accomplished in several ways: •C++ language features are used to make correct usage easy (if possible) and error-prone usage impossible or at least more difficult. For example, see the Mutex and Lock designs, and note how they interact.•Certain traditional concurrent programming features are considered so error-prone that they are not provided at all. For example, see the section called “Rationale for not providing Event Variables”.•Dangerous features, or features which may be misused, are identified as such in the documentation to make users aware of potential pitfalls.Flexibility Boost.Threads was designed to be flexible. This goal is often at odds with safety. When functionality might be compromised by the desire to keep the interface safe, Boost.Threads has been designed to provide the functionality, but to make it's use prohibitive for general use. In other words, the interfaces have been designed such that it's usually obvious when something is unsafe, and the documentation is written to explain why.Efficiency Boost.Threads was designed to be as efficient as possible. When building a library on top of another library there is always a danger that the result will be so much slower than the "native" API that programmers are inclined to ignore the higher level API. Boost.Threads was designed to minimize the chances of this occurring. The interfaces have been crafted to allow an implementation the greatest chance of being as efficient as possible. This goal is often at odds with the goal for safety. Every effort was made to ensure efficient implementations, but when in conflict safety has always taken precedence.
Iterative Phases
Another goal of Boost.Threads was to take a dynamic, iterative approach in its development. The computing industry is still exploring the concepts of parallel programming. Most thread libraries supply only simple primitive concepts for thread synchronization. These concepts are very simple, but it is very difficult to use them safely or to provide formal proofs for constructs built on top of them. There has been a lot of research into other concepts, such as in "Communicating Sequential Processes." Boost.Threads was designed in iterative steps, with each step providing the building blocks necessary for the next step and giving the researcher the tools necessary to explore new concepts in a portable manner.
Given the goal of following a dynamic, iterative approach Boost.Threads shall go through several growth cycles. Each phase in its development shall be roughly documented here.
Phase 1, Synchronization Primitives
Boost is all about providing high quality libraries with implementations for many platforms. Unfortunately, there's a big problem faced by developers wishing to supply such high quality libraries, namely thread-safety. The C++ standard doesn't address threads at all, but real world programs often make use of native threading support. A portable library that doesn't address the issue of thread-safety is therefore not much help to a programmer who wants to use the library in his multithreaded application. So there's a very great need for portable primitives that will allow the library developer to create thread-safe implementations. This need far out weighs the need for portable methods to create and manage threads.
Because of this need, the first phase of Boost.Threads focuses solely on providing portable primitive concepts for thread synchronization. Types provided in this phase include the boost::mutex, boost::try_mutex, boost::timed_mutex, boost::recursive_mutex, boost::recursive_try_mutex, boost::recursive_timed_mutex, and boost::lock_error. These are considered the "core" synchronization primitives, though there are others that will be added in later phases.
Phase 2, Thread Management and Thread Specific Storage
This phase addresses the creation and management of threads and provides a mechanism for thread specific storage (data associated with a thread instance). Thread management is a tricky issue in C++, so this phase addresses only the basic needs of multithreaded program. Later phases are likely to add additional functionality in this area. This phase of Boost.Threads adds the boost::thread and boost::thread_specific_ptr types. With these additions the Boost.Threads library can be considered minimal but complete.
The Next Phase
The next phase will address more advanced synchronization concepts, such as read/write mutexes and barriers.
Concepts
Concepts
Boost.Threads
currently supports two types of mutex concepts: ordinary Mutexes, which allow only one thread at a time to access a resource, and Read/Write Mutexes, which allow only one thread at a time to access a resource when it is being modified (the "Write" part of Read/Write), but allows multiple threads to access a resource when it is only being referenced (the "Read" part of Read/Write).
Mutexes
Note
Certain changes to the mutexes and lock concepts are currently under discussion. In particular, the combination of the multiple lock concepts into a single lock concept is likely, and the combination of the multiple mutex concepts into a single mutex concept is also possible.
A mutex (short for mutual-exclusion) object is used to serialize access to a resource shared between multiple threads. The Mutex concept, with TryMutex and TimedMutex refinements, formalize the requirements. A model that implements Mutex and its refinements has two states: locked and unlocked. Before using a shared resource, a thread locks a Boost.Threads mutex object (an object whose type is a model of Mutex or one of it's refinements), ensuring thread-safe access to the shared resource. When use of the shared resource is complete, the thread unlocks the mutex object, allowing another thread to acquire the lock and use the shared resource.
Traditional C thread APIs, like POSIX threads or the Windows thread APIs, expose functions to lock and unlock a mutex object. This is dangerous since it's easy to forget to unlock a locked mutex. When the flow of control is complex, with multiple return points, the likelihood of forgetting to unlock a mutex object becomes even greater. When exceptions are thrown, it becomes nearly impossible to ensure that the mutex object is unlocked properly when using these traditional API's. The result is deadlock.
Many C++ threading libraries use a pattern known as Scoped Locking[SchmidtStalRohnertBuschmann] to free the programmer from the need to explicitly lock and unlock mutex objects. With this pattern, a Lock concept is employed where the lock object's constructor locks the associated mutex object and the destructor automatically does the unlocking. The Boost.Threads library takes this pattern to the extreme in that Lock concepts are the only way to lock and unlock a mutex object: lock and unlock functions are not exposed by any Boost.Threads mutex objects. This helps to ensure safe usage patterns, especially when code throws exceptions.
Locking Strategies
Every mutex object follows one of several locking strategies. These strategies define the semantics for the locking operation when the calling thread already owns a lock on the mutex object.
Recursive Locking Strategy
With a recursive locking strategy, when a thread attempts to acquire a lock on the mutex object for which it already owns a lock, the operation is successful. Note the distinction between a thread, which may have multiple locks outstanding on a recursive mutex object, and a lock object, which even for a recursive mutex object cannot have any of its lock functions called multiple times without first calling unlock.
Internally a lock count is maintained and the owning thread must unlock the mutex object the same number of times that it locked it before the mutex object's state returns to unlocked. Since mutex objects in Boost.Threads expose locking functionality only through lock concepts, a thread will always unlock a mutex object the same number of times that it locked it. This helps to eliminate a whole set of errors typically found in traditional C style thread APIs.
Classes boost::recursive_mutex, boost::recursive_try_mutex and boost::recursive_timed_mutex use this locking strategy.
Checked Locking Strategy
With a checked locking strategy, when a thread attempts to acquire a lock on the mutex object for which the thread already owns a lock, the operation will fail with some sort of error indication. Further, attempts by a thread to unlock a mutex object that was not locked by the thread will also return some sort of error indication. In Boost.Threads, an exception of type boost::lock_error would be thrown in these cases.
Boost.Threads
does not currently provide any mutex objects that use this strategy.
Unchecked Locking Strategy
With an unchecked locking strategy, when a thread attempts to acquire a lock on a mutex object for which the thread already owns a lock the operation will deadlock. In general this locking strategy is less safe than a checked or recursive strategy, but it's also a faster strategy and so is employed by many libraries.
Boost.Threads
does not currently provide any mutex objects that use this strategy.
Unspecified Locking Strategy
With an unspecified locking strategy, when a thread attempts to acquire a lock on a mutex object for which the thread already owns a lock the operation results in undefined behavior.
In general a mutex object with an unspecified locking strategy is unsafe, and it requires programmer discipline to use the mutex object properly. However, this strategy allows an implementation to be as fast as possible with no restrictions on its implementation. This is especially true for portable implementations that wrap the native threading support of a platform. For this reason, the classes boost::mutex, boost::try_mutex and boost::timed_mutex use this locking strategy despite the lack of safety.
Scheduling Policies
Every mutex object follows one of several scheduling policies. These policies define the semantics when the mutex object is unlocked and there is more than one thread waiting to acquire a lock. In other words, the policy defines which waiting thread shall acquire the lock.
FIFO Scheduling Policy
With a FIFO ("First In First Out") scheduling policy, threads waiting for the lock will acquire it in a first-come-first-served order. This can help prevent a high priority thread from starving lower priority threads that are also waiting on the mutex object's lock.
Priority Driven Policy
With a Priority Driven scheduling policy, the thread with the highest priority acquires the lock. Note that this means that low-priority threads may never acquire the lock if the mutex object has high contention and there is always at least one high-priority thread waiting. This is known as thread starvation. When multiple threads of the same priority are waiting on the mutex object's lock one of the other scheduling priorities will determine which thread shall acquire the lock.
Unspecified Policy
The mutex object does not specify a scheduling policy. In order to ensure portability, all Boost.Threads mutex objects use an unspecified scheduling policy.
Mutex Concepts
Mutex Concept
A Mutex object has two states: locked and unlocked. Mutex object state can only be determined by a lock object meeting the appropriate lock concept requirements and constructed for the Mutex object.
A Mutex is NonCopyable.
For a Mutex type M and an object m of that type, the following expressions must be well-formed and have the indicated effects.
Table 1. Mutex Expressions

Expression
Effects
M m;
Constructs a mutex object m.
Postcondition: m is unlocked.
(&m)->~M();
Precondition: m is unlocked. Destroys a mutex object m.
M::scoped_lock
A model of ScopedLock

TryMutex Concept
A TryMutex is a refinement of Mutex. For a TryMutex type M and an object m of that type, the following expressions must be well-formed and have the indicated effects.
Table 2. TryMutex Expressions

Expression
Effects
M::scoped_try_lock
A model of ScopedTryLock

TimedMutex Concept
A TimedMutex is a refinement of TryMutex. For a TimedMutex type M and an object m of that type, the following expressions must be well-formed and have the indicated effects.
Table 3. TimedMutex Expressions

Expression
Effects
M::scoped_timed_lock
A model of ScopedTimedLock

Mutex Models
Boost.Threads
currently supplies six models of Mutex and its refinements.
Table 4. Mutex Models

Concept
Refines
Models
Mutex
boost::mutex
boost::recursive_mutex
TryMutex
Mutex
boost::try_mutex
boost::recursive_try_mutex
TimedMutex
TryMutex
boost::timed_mutex
boost::recursive_timed_mutex

Lock Concepts
A lock object provides a safe means for locking and unlocking a mutex object (an object whose type is a model of Mutex or one of its refinements). In other words they are an implementation of the Scoped Locking[SchmidtStalRohnertBuschmann] pattern. The ScopedLock, ScopedTryLock, and ScopedTimedLock concepts formalize the requirements.
Lock objects are constructed with a reference to a mutex object and typically acquire ownership of the mutex object by setting its state to locked. They also ensure ownership is relinquished in the destructor. Lock objects also expose functions to query the lock status and to manually lock and unlock the mutex object.
Lock objects are meant to be short lived, expected to be used at block scope only. The lock objects are not thread-safe. Lock objects must maintain state to indicate whether or not they've been locked and this state is not protected by any synchronization concepts. For this reason a lock object should never be shared between multiple threads.
Lock Concept
For a Lock type L and an object lk and const object clk of that type, the following expressions must be well-formed and have the indicated effects.
Table 5. Lock Expressions

Expression
Effects
(&lk)->~L();
if (locked()) unlock();
(&clk)->operator const void*()
Returns type void*, non-zero if the associated mutex object has been locked by clk, otherwise 0.
clk.locked()
Returns a bool, (&clk)->operator const void*() != 0
lk.lock()
Throws boost::lock_error if locked().
If the associated mutex object is already locked by some other thread, places the current thread in the Blocked state until the associated mutex is unlocked, after which the current thread is placed in the Ready state, eventually to be returned to the Running state. If the associated mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated mutex object.
Postcondition: locked() == true
lk.unlock()
Throws boost::lock_error if !locked().
Unlocks the associated mutex.
Postcondition: !locked()

ScopedLock Concept
A ScopedLock is a refinement of Lock. For a ScopedLock type L and an object lk of that type, and an object m of a type meeting the Mutex requirements, and an object b of type bool, the following expressions must be well-formed and have the indicated effects.
Table 6. ScopedLock Expressions

Expression
Effects
L lk(m);
Constructs an object lk, and associates mutex object m with it, then calls lock()
L lk(m,b);
Constructs an object lk, and associates mutex object m with it, then if b, calls lock()

TryLock Concept
A TryLock is a refinement of Lock. For a TryLock type L and an object lk of that type, the following expressions must be well-formed and have the indicated effects.
Table 7. TryLock Expressions

Expression
Effects
lk.try_lock()
Throws boost::lock_error if locked().
Makes a non-blocking attempt to lock the associated mutex object, returning true if the lock attempt is successful, otherwise false. If the associated mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated mutex object.

ScopedTryLock Concept
A ScopedTryLock is a refinement of TryLock. For a ScopedTryLock type L and an object lk of that type, and an object m of a type meeting the TryMutex requirements, and an object b of type bool, the following expressions must be well-formed and have the indicated effects.
Table 8. ScopedTryLock Expressions

Expression
Effects
L lk(m);
Constructs an object lk, and associates mutex object m with it, then calls try_lock()
L lk(m,b);
Constructs an object lk, and associates mutex object m with it, then if b, calls lock()

TimedLock Concept
A TimedLock is a refinement of TryLock. For a TimedLock type L and an object lk of that type, and an object t of type boost::xtime, the following expressions must be well-formed and have the indicated effects.
Table 9. TimedLock Expressions

Expression
Effects
lk.timed_lock(t)
Throws boost::lock_error if locked().
Makes a blocking attempt to lock the associated mutex object, and returns true if successful within the specified time t, otherwise false. If the associated mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated mutex object.

ScopedTimedLock Concept
A ScopedTimedLock is a refinement of TimedLock. For a ScopedTimedLock type L and an object lk of that type, and an object m of a type meeting the TimedMutex requirements, and an object b of type bool, and an object t of type boost::xtime, the following expressions must be well-formed and have the indicated effects.
Table 10. ScopedTimedLock Expressions

Expression
Effects
L lk(m,t);
Constructs an object lk, and associates mutex object m with it, then calls timed_lock(t)
L lk(m,b);
Constructs an object lk, and associates mutex object m with it, then if b, calls lock()

Lock Models
Boost.Threads
currently supplies twelve models of Lock and its refinements.
Table 11. Lock Models

Concept
Refines
Models
Lock
ScopedLock
Lock
boost::mutex::scoped_lock
boost::recursive_mutex::scoped_lock
boost::try_mutex::scoped_lock
boost::recursive_try_mutex::scoped_lock
boost::timed_mutex::scoped_lock
boost::recursive_timed_mutex::scoped_lock
TryLock
Lock
ScopedTryLock
TryLock
boost::try_mutex::scoped_try_lock
boost::recursive_try_mutex::scoped_try_lock
boost::timed_mutex::scoped_try_lock
boost::recursive_timed_mutex::scoped_try_lock
TimedLock
TryLock
ScopedTimedLock
TimedLock
boost::timed_mutex::scoped_timed_lock
boost::recursive_timed_mutex::scoped_timed_lock

Read/Write Mutexes
Note
Since the read/write mutex and related classes are new, both interface and implementation are liable to change in future releases of Boost.Threads. The lock concepts and lock promotion and demotion in particular are still under discussion and very likely to change.
A read/write mutex (short for reader/writer mutual-exclusion) object is used to serialize access to a resource shared between multiple threads, where multiple "readers" can share simultaneous access, but "writers" require exclusive access. The ReadWriteMutex concept, with TryReadWriteMutex and TimedReadWriteMutex refinements formalize the requirements. A model that implements ReadWriteMutex and its refinements has three states: read-locked, write-locked, and unlocked. Before reading from a shared resource, a thread read-locks a Boost.Threads read/write mutex object (an object whose type is a model of ReadWriteMutex or one of it's refinements), ensuring thread-safe access for reading from the shared resource. Before writing to a shared resource, a thread write-locks a Boost.Threads read/write mutex object (an object whose type is a model of ReadWriteMutex or one of it's refinements), ensuring thread-safe access for altering the shared resource. When use of the shared resource is complete, the thread unlocks the mutex object, allowing another thread to acquire the lock and use the shared resource.
Traditional C thread APIs that provide read/write mutex primitives (like POSIX threads) expose functions to lock and unlock a mutex object. This is dangerous since it's easy to forget to unlock a locked mutex. When the flow of control is complex, with multiple return points, the likelihood of forgetting to unlock a mutex object becomes even greater. When exceptions are thrown, it becomes nearly impossible to ensure that the mutex object is unlocked properly when using these traditional API's. The result is deadlock.
Many C++ threading libraries use a pattern known as Scoped Locking[SchmidtStalRohnertBuschmann] to free the programmer from the need to explicitly lock and unlock read/write mutex objects. With this pattern, a Read/Write Lock concept is employed where the lock object's constructor locks the associated read/write mutex object and the destructor automatically does the unlocking. The Boost.Threads library takes this pattern to the extreme in that Read/Write Lock concepts are the only way to lock and unlock a read/write mutex object: lock and unlock functions are not exposed by any Boost.Threads read/write mutex objects. This helps to ensure safe usage patterns, especially when code throws exceptions.
Locking Strategies
Every read/write mutex object follows one of several locking strategies. These strategies define the semantics for the locking operation when the calling thread already owns a lock on the read/write mutex object.
Recursive Locking Strategy
With a recursive locking strategy, when a thread attempts to acquire a lock on a read/write mutex object for which it already owns a lock, the operation is successful, except in the case where a thread holding a read-lock attempts to obtain a write lock, in which case a boost::lock_error exception will be thrown. Note the distinction between a thread, which may have multiple locks outstanding on a recursive read/write mutex object, and a lock object, which even for a recursive read/write mutex object cannot have any of its lock functions called multiple times without first calling unlock.

Lock Type Held
Lock Type Requested
Action
read-lock
read-lock
Grant the read-lock immediately
read-lock
write-lock
If this thread is the only holder of the read-lock, grants the write lock immediately. Otherwise throws a boost::lock_error exception.
write-locked
read-lock
Grants the (additional) read-lock immediately.
write-locked
write-lock
Grant the write-lock immediately

Internally a lock count is maintained and the owning thread must unlock the mutex object the same number of times that it locked it before the mutex object's state returns to unlocked. Since mutex objects in Boost.Threads expose locking functionality only through lock concepts, a thread will always unlock a mutex object the same number of times that it locked it. This helps to eliminate a whole set of errors typically found in traditional C style thread APIs.
Boost.Threads
does not currently provide any read/write mutex objects that use this strategy. A successful implementation of this locking strategy may require thread identification.
Checked Locking Strategy
With a checked locking strategy, when a thread attempts to acquire a lock on the mutex object for which the thread already owns a lock, the operation will fail with some sort of error indication, except in the case of multiple read-lock acquisition which is a normal operation for ANY ReadWriteMutex. Further, attempts by a thread to unlock a mutex that was not locked by the thread will also return some sort of error indication. In Boost.Threads, an exception of type boost::lock_error would be thrown in these cases.

Lock Type Held
Lock Type Requested
Action
read-lock
read-lock
Grant the read-lock immediately
read-lock
write-lock
Throw boost::lock_error
write-locked
read-lock
Throw boost::lock_error
write-locked
write-lock
Throw boost::lock_error

Boost.Threads
does not currently provide any read/write mutex objects that use this strategy. A successful implementation of this locking strategy may require thread identification.
Unchecked Locking Strategy
With an unchecked locking strategy, when a thread attempts to acquire a lock on the read/write mutex object for which the thread already owns a lock, the operation will deadlock. In general this locking strategy is less safe than a checked or recursive strategy, but it can be a faster strategy and so is employed by many libraries.

Lock Type Held
Lock Type Requested
Action
read-lock
read-lock
Grant the read-lock immediately
read-lock
write-lock
Deadlock
write-locked
read-lock
Deadlock
write-locked
write-lock
Deadlock

Boost.Threads
does not currently provide any mutex objects that use this strategy. For ReadWriteMutexes on platforms that contain natively recursive synchronization primitives, implementing a guaranteed-deadlock can actually involve extra work, and would likely require thread identification.
Unspecified Locking Strategy
With an unspecified locking strategy, when a thread attempts to acquire a lock on a read/write mutex object for which the thread already owns a lock, the operation results in undefined behavior. When a read/write mutex object has an unspecified locking strategy the programmer must assume that the read/write mutex object instead uses an unchecked strategy as the worse case, although some platforms may exhibit a mix of unchecked and recursive behavior.

Lock Type Held
Lock Type Requested
Action
read-lock
read-lock
Grant the read-lock immediately
read-lock
write-lock
Undefined
, but generally deadlock
write-locked
read-lock
Undefined
, but generally deadlock
write-locked
write-lock
Undefined
, but generally deadlock

In general a read/write mutex object with an unspecified locking strategy is unsafe, and it requires programmer discipline to use the read/write mutex object properly. However, this strategy allows an implementation to be as fast as possible with no restrictions on its implementation. This is especially true for portable implementations that wrap the native threading support of a platform. For this reason, the classes read_write_mutex, try_read_write_mutex, and timed_read_write_mutex use this locking strategy despite the lack of safety.
Thread Identification
ReadWriteMutexes can support specific Locking Strategies (recursive and checked) which help to detect and protect against self-deadlock. Self-deadlock can occur when a holder of a locked ReadWriteMutex attempts to obtain another lock. Given an implemention I which is susceptible to self-deadlock but otherwise correct and efficient, a recursive or checked implementation Ir or Ic can use the same basic implementation, but make special checks against self-deadlock by tracking the identities of thread(s) currently holding locks. This approach makes deadlock detection othrogonal to the basic ReadWriteMutex implementaion.
Alternatively, a different basic implementation for ReadWriteMutex concepts, I' (I-Prime) may exist which uses recursive or checked versions of synchronization primitives to produce a recursive or checked ReadWriteMutex while still providing flexibility in terms of Scheduling Policies.
Please refer to the Boost.Threads read/write mutex concept documentation for a discussion of locking strategies. The read/write mutex supports only the unspecified locking strategy. ReadWriteMutexes are parameterized on a Mutex type which they use to control write-locking and access to internal state.
Lock Promotion
ReadWriteMutexes can support lock promotion, where a mutex which is in the read-locked state transitions to a write-locked state without releasing the lock. Lock promotion can be tricky to implement; for instance, extra care must be taken to ensure that only one thread holding a read-lock can block awaiting promotion at any given time. If more than one read-lock holder is allowed to enter a blocked state while waiting to be promoted, deadlock will result since both threads will be waiting for the other to release their read-lock.
Currently, Boost.Threads supports lock promotion through promote(), try_promote(), and timed_promote() operations.
Lock Demotion
ReadWriteMutexes can support lock demotion, where a mutex which is in the write-locked state transitions to a read-locked state without releasing the lock. Since by definition only one thread at a time may hold a write-lock, the problem with deadlock that can occur during lock promotion is not a problem for lock demotion.
Currently, Boost.Threads supports lock demotion through demote(), try_demote(), and timed_demote() operations.
Scheduling Policies
Every read/write mutex object follows one of several scheduling policies. These policies define the semantics when the mutex object is unlocked and there is more than one thread waiting to acquire a lock. In other words, the policy defines which waiting thread shall acquire the lock. For a read/write mutex, it is particularly important to define the behavior when threads are requesting both read and write access simultaneously. This will be referred to as "inter-class scheduling" because it describes the scheduling between two classes of threads (those waiting for a read lock and those waiting for a write lock).
For some types of inter-class scheduling, an "intra-class" scheduling policy can also be defined that will describe the order in which waiting threads of the same class (i.e., those waiting for the same type of lock) will acquire the thread.
Inter-Class Scheduling Policies
ReaderPriority
With ReaderPriority scheduling, any pending request for a read-lock will have priority over a pending request for a write-lock, irrespective of the current lock state of the read/write mutex, and irrespective of the relative order that the pending requests arrive.

Current mutex state
Request Type
Action
unlocked
read-lock
Grant the read-lock immediately
read-locked
read-lock
Grant the additional read-lock immediately.
write-locked
read-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock (or until the specified time, if any). A read-lock will be granted to all pending readers before any other thread can acquire a write-lock. TODO: try-lock, timed-lock.
unlocked
write-lock
Grant the write-lock immediately, if and only if there are no pending read-lock requests. TODO: try-lock, timed-lock.
read-locked
write-lock
Wait to acquire the lock until all threads holding read-locks release their locks AND no requests for read-locks exist. If other write-lock requests exist, the lock is granted in accordance with the intra-class scheduling policy. TODO: try-lock, timed-lock.
write-locked
write-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock AND no requests for read-locks exist. If other write-lock requests exist, the lock is granted in accordance with the intra-class scheduling policy. TODO: try-lock, timed-lock.
read-locked
promote
TODO
write-locked
demote
TODO

WriterPriority
With WriterPriority scheduling, any pending request for a write-lock will have priority over a pending request for a read-lock, irrespective of the current lock state of the read/write mutex, and irrespective of the relative order that the pending requests arrive.

Current mutex state
Request Type
Action
unlocked
read-lock
Grant the read-lock immediately.
read-locked
read-lock
Grant the additional read-lock immediately, IF no outstanding requests for a write-lock exist; otherwise TODO. TODO: try-lock, timed-lock.
write-locked
read-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock. The read lock will be granted once no other outstanding write-lock requests exist. TODO: try-lock, timed-lock.
unlocked
write-lock
Grant the write-lock immediately.
read-locked
write-lock
Wait to acquire the lock until all threads holding read-locks release their locks. If other write-lock requests exist, the lock is granted in accordance with the intra-class scheduling policy. This request will be granted before any new read-lock requests are granted. TODO: try-lock, timed-lock.
write-locked
write-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock. If other write-lock requests exist, the lock is granted in accordance with the intra-class scheduling policy. This request will be granted before any new read-lock requests are granted. TODO: try-lock, timed-lock.
read-locked
promote
TODO
write-locked
demote
TODO

AlternatingPriority/ManyReads
With AlternatingPriority/ManyReads scheduling, reader or writer starvation is avoided by alternatively granting read or write access when pending requests exist for both types of locks. Outstanding read-lock requests are treated as a group when it is the "readers' turn"

Current mutex state
Request Type
Action
unlocked
read-lock
Grant the read-lock immediately.
read-locked
read-lock
Grant the additional read-lock immediately, IF no outstanding requests for a write-lock exist. If outstanding write-lock requests exist, this lock will not be granted until at least one of the write-locks is granted and released. If other read-lock requests exist, all read-locks will be granted as a group. TODO: try-lock, timed-lock.
write-locked
read-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock. If other outstanding write-lock requests exist, they will have to wait until all current read-lock requests are serviced. TODO: try-lock, timed-lock.
unlocked
write-lock
Grant the write-lock immediately.
read-locked
write-lock
Wait to acquire the lock until all threads holding read-locks release their locks.
If other write-lock requests exist, this lock will be granted to one of them in accordance with the intra-class scheduling policy.
TODO: try-lock, timed-lock.
write-locked
write-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock. If other outstanding read-lock requests exist, this lock will not be granted until all of the currently waiting read-locks are granted and released. If other write-lock requests exist, this lock will be granted in accordance with the intra-class scheduling policy. TODO: try-lock, timed-lock.
read-locked
promote
TODO
write-locked
demote
TODO

AlternatingPriority/SingleRead
With AlternatingPriority/SingleRead scheduling, reader or writer starvation is avoided by alternatively granting read or write access when pending requests exist for both types of locks. Outstanding read-lock requests are services one at a time when it is the "readers' turn"

Current mutex state
Request Type
Action
unlocked
read-lock
Grant the read-lock immediately.
read-locked
read-lock
Grant the additional read-lock immediately, IF no outstanding requests for a write-lock exist. If outstanding write-lock requests exist, this lock will not be granted until at least one of the write-locks is granted and released. TODO: try-lock, timed-lock.
write-locked
read-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock.
If other outstanding write-lock requests exist, exactly one read-lock request will be granted before the next write-lock is granted.
TODO: try-lock, timed-lock.
unlocked
write-lock
Grant the write-lock immediately.
read-locked
write-lock
Wait to acquire the lock until all threads holding read-locks release their locks.
If other write-lock requests exist, this lock will be granted to one of them in accordance with the intra-class scheduling policy.
write-locked
write-lock
Wait to acquire the lock until the thread holding the write-lock releases its lock. If other outstanding read-lock requests exist, this lock can not be granted until exactly one read-lock request is granted and released. If other write-lock requests exist, this lock will be granted in accordance with the intra-class scheduling policy. TODO: try-lock, timed-lock.
read-locked
promote
TODO
write-locked
demote
TODO

Intra-Class Scheduling Policies
Please refer to the section called “Scheduling Policies” for a discussion of mutex scheduling policies, which are identical to read/write mutex intra-class scheduling policies.
For threads waiting to obtain write-locks, the read/write mutex supports only the Unspecified intra-class scheduling policy. That is, given a set of threads waiting for write-locks, the order, relative to one another, in which they receive the write-lock is unspecified.
For threads waiting to obtain read-locks, the read/write mutex supports only the Unspecified intra-class scheduling policy. That is, given a set of threads waiting for read-locks, the order, relative to one another, in which they receive the read-lock is unspecified.
Mutex Concepts
ReadWriteMutex Concept
A ReadWriteMutex object has three states: read-locked, write-locked, and unlocked. ReadWriteMutex object state can only be determined by a lock object meeting the appropriate lock concept requirements and constructed for the ReadWriteMutex object.
A ReadWriteMutex is NonCopyable.
For a ReadWriteMutex type M, and an object m of that type, the following expressions must be well-formed and have the indicated effects.
Table 12. ReadWriteMutex Expressions

Expression
Effects
M m;
Constructs a read/write mutex object m. Post-condition: m is unlocked.
(&m)->~M();
Precondition: m is unlocked. Destroys a read/write mutex object m.
M::scoped_read_write_lock
A type meeting the ScopedReadWriteLock requirements.
M::scoped_read_lock
A type meeting the ScopedLock requirements.
M::scoped_write_lock
A type meeting the ScopedLock requirements.

TryReadWriteMutex Concept
A TryReadWriteMutex is a refinement of ReadWriteMutex. For a TryReadWriteMutex type M and an object m of that type, the following expressions must be well-formed and have the indicated effects.
Table 13. TryReadWriteMutex Expressions

Expression
Effects
M::scoped_try_read_write_lock
A type meeting the ScopedTryReadWriteLock requirements.
M::scoped_try_read_lock
A type meeting the ScopedTryLock requirements.
M::scoped_try_write_lock
A type meeting the ScopedTryLock requirements.

TimedReadWriteMutex Concept
A TimedReadWriteMutex is a refinement of TryReadWriteMutex. For a TimedReadWriteMutex type M and an object m of that type the following expressions must be well-formed and have the indicated effects.
Table 14. TimedReadWriteMutex Expressions

Expression
Effects
M::scoped_timed_read_write_lock
A type meeting the ScopedTimedReadWriteLock requirements.
M::scoped_timed_read_lock
A type meeting the ScopedTimedLock requirements.
M::scoped_timed_write_lock
A type meeting the ScopedTimedLock requirements.

Mutex Models
Boost.Threads
currently supplies three models of ReadWriteMutex and its refinements.
Table 15. Mutex Models

Concept
Refines
Models
ReadWriteMutex
boost::read_write_mutex
TryReadWriteMutex
ReadWriteMutex
boost::try_read_write_mutex
TimedReadWriteMutex
TryReadWriteMutex
boost::timed_read_write_mutex

Lock Concepts
A read/write lock object provides a safe means for locking and unlocking a read/write mutex object (an object whose type is a model of ReadWriteMutex or one of its refinements). In other words they are an implementation of the Scoped Locking[SchmidtStalRohnertBuschmann] pattern. The ScopedReadWriteLock, ScopedTryReadWriteLock, and ScopedTimedReadWriteLock concepts formalize the requirements.
Read/write lock objects are constructed with a reference to a read/write mutex object and typically acquire ownership of the read/write mutex object by setting its state to locked. They also ensure ownership is relinquished in the destructor. Lock objects also expose functions to query the lock status and to manually lock and unlock the read/write mutex object.
Read/write lock objects are meant to be short lived, expected to be used at block scope only. The read/write lock objects are not thread-safe. Read/write lock objects must maintain state to indicate whether or not they've been locked and this state is not protected by any synchronization concepts. For this reason a read/write lock object should never be shared between multiple threads.
ReadWriteLock Concept
For a read/write lock type L and an object lk and const object clk of that type, the following expressions must be well-formed and have the indicated effects.
Table 16. ReadWriteLock Expressions

Expression
Effects
(&lk)->~L();
if (locked()) unlock();
(&clk)->operator const void*()
Returns type void*, non-zero if the associated read/write mutex object has been either read-locked or write-locked by clk, otherwise 0.
clk.locked()
Returns a bool, (&clk)->operator const void*() != 0
clk.state()
Returns an enumeration constant of type read_write_lock_state: read_write_lock_state::read_locked if the associated read/write mutex object has been read-locked by clk, read_write_lock_state::write_locked if it has been write-locked by clk, and read_write_lock_state::unlocked if has not been locked by clk.
clk.read_locked()
Returns a bool, (&clk)->state() == read_write_lock_state::read_locked.
clk.write_locked()
Returns a bool, (&clk)->state() == read_write_lock_state::write_locked.
lk.read_lock()
Throws boost::lock_error if locked().
If the associated read/write mutex object is already read-locked by some other thread, the effect depends on the inter-class scheduling policy of the associated read/write mutex: either immediately obtains an additional read-lock on the associated read/write mutex, or places the current thread in the Blocked state until the associated read/write mutex is unlocked, after which the current thread is placed in the Ready state, eventually to be returned to the Running state.
If the associated read/write mutex object is already write-locked by some other thread, places the current thread in the Blocked state until the associated read/write mutex is unlocked, after which the current thread is placed in the Ready state, eventually to be returned to the Running state.
If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
Postcondition: state() == read_write_lock_state::read_locked
lk.write_lock()
Throws boost::lock_error if locked().
If the associated read/write mutex object is already locked by some other thread, places the current thread in the Blocked state until the associated read/write mutex is unlocked, after which the current thread is placed in the Ready state, eventually to be returned to the Running state.
If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
Postcondition: state() == read_write_lock_state::write_locked
lk.demote()
Throws boost::lock_error if state() != read_write_lock_state::write_locked.
Converts the lock held on the associated read/write mutex object from a write-lock to a read-lock without releasing the lock.
Postcondition: state() == read_write_lock_state::read_locked
lk.promote()
Throws boost::lock_error if state() != read_write_lock_state::read_locked or if the lock cannot be promoted because another lock on the same mutex is already waiting to be promoted.
Makes a blocking attempt to convert the lock held on the associated read/write mutex object from a read-lock to a write-lock without releasing the lock.
lk.unlock()
Throws boost::lock_error if !locked().
Unlocks the associated read/write mutex.
Postcondition: !locked()

ScopedReadWriteLock Concept
A ScopedReadWriteLock is a refinement of ReadWriteLock. For a ScopedReadWriteLock type L and an object lk of that type, and an object m of a type meeting the ReadWriteMutex requirements, and an object s of type read_write_lock_state, the following expressions must be well-formed and have the indicated effects.
Table 17. ScopedReadWriteLock Expressions

Expression
Effects
L lk(m,s);
Constructs an object lk and associates read/write mutex object m with it, then: if s == read_write_lock_state::read_locked, calls read_lock(); if s==read_write_lock_state::write_locked, calls write_lock().

TryReadWriteLock Expressions
A TryReadWriteLock is a refinement of ReadWriteLock. For a TryReadWriteLock type L and an object lk of that type, the following expressions must be well-formed and have the indicated effects.
Table 18. TryReadWriteLock Expressions

Expression
Effects
lk.try_read_lock()
Throws boost::lock_error if locked().
Makes a non-blocking attempt to read-lock the associated read/write mutex object, returning true if the attempt is successful, otherwise false. If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
lk.try_write_lock()
Throws boost::lock_error if locked().
Makes a non-blocking attempt to write-lock the associated read/write mutex object, returning true if the attempt is successful, otherwise false. If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
lk.try_demote()
Throws boost::lock_error if state() != read_write_lock_state::write_locked.
Makes a non-blocking attempt to convert the lock held on the associated read/write mutex object from a write-lock to a read-lock without releasing the lock, returning true if the attempt is successful, otherwise false.
lk.try_promote()
Throws boost::lock_error if state() != read_write_lock_state::read_locked.
Makes a non-blocking attempt to convert the lock held on the associated read/write mutex object from a read-lock to a write-lock without releasing the lock, returning true if the attempt is successful, otherwise false.

ScopedTryReadWriteLock Expressions
A ScopedTryReadWriteLock is a refinement of TryReadWriteLock. For a ScopedTryReadWriteLock type L and an object lk of that type, and an object m of a type meeting the TryReadWriteMutex requirements, and an object s of type read_write_lock_state, and an object b of type blocking_mode, the following expressions must be well-formed and have the indicated effects.
Table 19. ScopedTryReadWriteLock Expressions

Expression
Effects
L lk(m,s,b);
Constructs an object lk and associates read/write mutex object m with it, then: if s == read_write_lock_state::read_locked, calls read_lock() if b, otherwise try_read_lock(); if s==read_write_lock_state::write_locked, calls write_lock() if b, otherwise try_write_lock.

TimedReadWriteLock Concept
A TimedReadWriteLock is a refinement of TryReadWriteLock. For a TimedReadWriteLock type L and an object lk of that type, and an object t of type boost::xtime, the following expressions must be well-formed and have the indicated effects.
Table 20. TimedReadWriteLock Expressions

Expression
Effects
lk.timed_read_lock(t)
Throws boost::lock_error if locked().
Makes a blocking attempt to read-lock the associated read/write mutex object, and returns true if successful within the specified time t, otherwise false. If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
lk.timed_write_lock(t)
Throws boost::lock_error if locked().
Makes a blocking attempt to write-lock the associated read/write mutex object, and returns true if successful within the specified time t, otherwise false. If the associated read/write mutex object is already locked by the same thread the behavior is dependent on the locking strategy of the associated read/write mutex object.
lk.timed_demote(t)
Throws boost::lock_error if state() != read_write_lock_state::write_locked.
Makes a blocking attempt to convert the lock held on the associated read/write mutex object from a write-lock to a read-lock without releasing the lock, returning true if the attempt is successful in the specified time t, otherwise false.
lk.timed_promote(t)
Throws boost::lock_error if state() != read_write_lock_state::read_locked.
Makes a blocking attempt to convert the lock held on the associated read/write mutex object from a read-lock to a write-lock without releasing the lock, returning true if the attempt is successful in the specified time t, otherwise false.

ScopedTimedReadWriteLock Concept
A ScopedTimedReadWriteLock is a refinement of TimedReadWriteLock. For a ScopedTimedReadWriteLock type L and an object lk of that type, and an object m of a type meeting the TimedReadWriteMutex requirements, and an object s of type read_write_lock_state, and an object t of type boost::xtime, and an object b of type blocking_mode, the following expressions must be well-formed and have the indicated effects.
Table 21. ScopedTimedReadWriteLock Expressions

Expression
Effects
L lk(m,s,b);
Constructs an object lk and associates read/write mutex object m with it, then: if s == read_write_lock_state::read_locked, calls read_lock() if b, otherwise try_read_lock(); if s==read_write_lock_state::write_locked, calls write_lock() if b, otherwise try_write_lock.
L lk(m,s,t);
Constructs an object lk and associates read/write mutex object m with it, then: if s == read_write_lock_state::read_locked, calls timed_read_lock(t); if s==read_write_lock_state::write_locked, calls timed_write_lock(t).

Lock Models
Boost.Threads
currently supplies six models of ReadWriteLock and its refinements.
Table 22. Lock Models

Concept
Refines
Models
ReadWriteLock
ScopedReadWriteLock
ReadWriteLock
boost::read_write_mutex::scoped_read_write_lock
boost::try_read_write_mutex::scoped_read_write_lock
boost::timed_read_write_mutex::scoped_read_write_lock
TryReadWriteLock
ReadWriteLock
ScopedTryReadWriteLock
TryReadWriteLock
boost::try_read_write_mutex::scoped_try_read_write_lock
boost::timed_read_write_mutex::scoped_try_read_write_lock
TimedReadWriteLock
TryReadWriteLock
ScopedTimedReadWriteLock
TimedReadWriteLock
boost::timed_read_write_mutex::scoped_timed_read_write_lock

Rationale
Rationale
This page explains the rationale behind various design decisions in the Boost.Threads library. Having the rationale documented here should explain how we arrived at the current design as well as prevent future rehashing of discussions and thought processes that have already occurred. It can also give users a lot of insight into the design process required for this library.
Rationale for the Creation of Boost.Threads
Processes often have a degree of "potential parallelism" and it can often be more intuitive to design systems with this in mind. Further, these parallel processes can result in more responsive programs. The benefits for multithreaded programming are quite well known to most modern programmers, yet the C++ language doesn't directly support this concept.
Many platforms support multithreaded programming despite the fact that the language doesn't support it. They do this through external libraries, which are, unfortunately, platform specific. POSIX has tried to address this problem through the standardization of a "pthread" library. However, this is a standard only on POSIX platforms, so its portability is limited.
Another problem with POSIX and other platform specific thread libraries is that they are almost universally C based libraries. This leaves several C++ specific issues unresolved, such as what happens when an exception is thrown in a thread. Further, there are some C++ concepts, such as destructors, that can make usage much easier than what's available in a C library.
What's truly needed is C++ language support for threads. However, the C++ standards committee needs existing practice or a good proposal as a starting point for adding this to the standard.
The Boost.Threads library was developed to provide a C++ developer with a portable interface for writing multithreaded programs on numerous platforms. There's a hope that the library can be the basis for a more detailed proposal for the C++ standards committee to consider for inclusion in the next C++ standard.
Rationale for the Low Level Primitives Supported in Boost.Threads
The Boost.Threads library supplies a set of low level primitives for writing multithreaded programs, such as mutexes and condition variables. In fact, the first release of Boost.Threads supports only these low level primitives. However, computer science research has shown that use of these primitives is difficult since it's difficult to mathematically prove that a usage pattern is correct, meaning it doesn't result in race conditions or deadlocks. There are several algebras (such as CSP, CCS and Join calculus) that have been developed to help write provably correct parallel processes. In order to prove the correctness these processes must be coded using higher level abstractions. So why does Boost.Threads support the lower level concepts?
The reason is simple: the higher level concepts need to be implemented using at least some of the lower level concepts. So having portable lower level concepts makes it easier to develop the higher level concepts and will allow researchers to experiment with various techniques.
Beyond this theoretical application of higher level concepts, however, the fact remains that many multithreaded programs are written using only the lower level concepts, so they are useful in and of themselves, even if it's hard to prove that their usage is correct. Since many users will be familiar with these lower level concepts but unfamiliar with any of the higher level concepts, supporting the lower level concepts provides greater accessibility.
Rationale for the Lock Design
Programmers who are used to multithreaded programming issues will quickly note that the Boost.Threads design for mutex lock concepts is not thread-safe (this is clearly documented as well). At first this may seem like a serious design flaw. Why have a multithreading primitive that's not thread-safe itself?
A lock object is not a synchronization primitive. A lock object's sole responsibility is to ensure that a mutex is both locked and unlocked in a manner that won't result in the common error of locking a mutex and then forgetting to unlock it. This means that instances of a lock object are only going to be created, at least in theory, within block scope and won't be shared between threads. Only the mutex objects will be created outside of block scope and/or shared between threads. Though it's possible to create a lock object outside of block scope and to share it between threads, to do so would not be a typical usage (in fact, to do so would likely be an error). Nor are there any cases when such usage would be required.
Lock objects must maintain some state information. In order to allow a program to determine if a try_lock or timed_lock was successful the lock object must retain state indicating the success or failure of the call made in its constructor. If a lock object were to have such state and remain thread-safe it would need to synchronize access to the state information which would result in roughly doubling the time of most operations. Worse, since checking the state can occur only by a call after construction, we'd have a race condition if the lock object were shared between threads.
So, to avoid the overhead of synchronizing access to the state information and to avoid the race condition, the Boost.Threads library simply does nothing to make lock objects thread-safe. Instead, sharing a lock object between threads results in undefined behavior. Since the only proper usage of lock objects is within block scope this isn't a problem, and so long as the lock object is properly used there's no danger of any multithreading issues.
Rationale for NonCopyable Thread Type
Programmers who are used to C libraries for multithreaded programming are likely to wonder why Boost.Threads uses a noncopyable design for boost::thread. After all, the C thread types are copyable, and you often have a need for copying them within user code. However, careful comparison of C designs to C++ designs shows a flaw in this logic.
All C types are copyable. It is, in fact, not possible to make a noncopyable type in C. For this reason types that represent system resources in C are often designed to behave very similarly to a pointer to dynamic memory. There's an API for acquiring the resource and an API for releasing the resource. For memory we have pointers as the type and alloc/free for the acquisition and release APIs. For files we have FILE* as the type and fopen/fclose for the acquisition and release APIs. You can freely copy instances of the types but must manually manage the lifetime of the actual resource through the acquisition and release APIs.
C++ designs recognize that the acquisition and release APIs are error prone and try to eliminate possible errors by acquiring the resource in the constructor and releasing it in the destructor. The best example of such a design is the std::iostream set of classes which can represent the same resource as the FILE* type in C. A file is opened in the std::fstream's constructor and closed in its destructor. However, if an iostream were copyable it could lead to a file being closed twice, an obvious error, so the std::iostream types are noncopyable by design. This is the same design used by boost::thread, which is a simple and easy to understand design that's consistent with other C++ standard types.
During the design of boost::thread it was pointed out that it would be possible to allow it to be a copyable type if some form of "reference management" were used, such as ref-counting or ref-lists, and many argued for a boost::thread_ref design instead. The reasoning was that copying "thread" objects was a typical need in the C libraries, and so presumably would be in the C++ libraries as well. It was also thought that implementations could provide more efficient reference management than wrappers (such as boost::shared_ptr) around a noncopyable thread concept. Analysis of whether or not these arguments would hold true doesn't appear to bear them out. To illustrate the analysis we'll first provide pseudo-code illustrating the six typical usage patterns of a thread object.
1. Use case: Simple creation of a thread.
void foo() { create_thread(&bar); }
2. Use case: Creation of a thread that's later joined.
void foo() { thread = create_thread(&bar); join(thread); }
3. Use case: Simple creation of several threads in a loop.
void foo() { for (int i=0; i<NUM_THREADS; ++i) create_thread(&bar); }
4. Use case: Creation of several threads in a loop which are later joined.
void foo() { for (int i=0; i<NUM_THREADS; ++i) threads[i] = create_thread(&bar); for (int i=0; i<NUM_THREADS; ++i) threads[i].join(); }
5. Use case: Creation of a thread whose ownership is passed to another object/method.
void foo() { thread = create_thread(&bar); manager.owns(thread); }
6. Use case: Creation of a thread whose ownership is shared between multiple objects.
void foo() { thread = create_thread(&bar); manager1.add(thread); manager2.add(thread); }
Of these usage patterns there's only one that requires reference management (number 6). Hopefully it's fairly obvious that this usage pattern simply won't occur as often as the other usage patterns. So there really isn't a "typical need" for a thread concept, though there is some need.
Since the need isn't typical we must use different criteria for deciding on either a thread_ref or thread design. Possible criteria include ease of use and performance. So let's analyze both of these carefully.
With ease of use we can look at existing experience. The standard C++ objects that represent a system resource, such as std::iostream, are noncopyable, so we know that C++ programmers must at least be experienced with this design. Most C++ developers are also used to smart pointers such as boost::shared_ptr, so we know they can at least adapt to a thread_ref concept with little effort. So existing experience isn't going to lead us to a choice.
The other thing we can look at is how difficult it is to use both types for the six usage patterns above. If we find it overly difficult to use a concept for any of the usage patterns there would be a good argument for choosing the other design. So we'll code all six usage patterns using both designs.
1. Comparison: simple creation of a thread.
void foo() { thread thrd(&bar); } void foo() { thread_ref thrd = create_thread(&bar); }
2. Comparison: creation of a thread that's later joined.
void foo() { thread thrd(&bar); thrd.join(); } void foo() { thread_ref thrd = create_thread(&bar);thrd->join(); }
3. Comparison: simple creation of several threads in a loop.
void foo() { for (int i=0; i<NUM_THREADS; ++i) thread thrd(&bar); } void foo() { for (int i=0; i<NUM_THREADS; ++i) thread_ref thrd = create_thread(&bar); }
4. Comparison: creation of several threads in a loop which are later joined.
void foo() { std::auto_ptr<thread> threads[NUM_THREADS]; for (int i=0; i<NUM_THREADS; ++i) threads[i] = std::auto_ptr<thread>(new thread(&bar)); for (int i= 0; i<NUM_THREADS; ++i)threads[i]->join(); } void foo() { thread_ref threads[NUM_THREADS]; for (int i=0; i<NUM_THREADS; ++i) threads[i] = create_thread(&bar); for (int i= 0; i<NUM_THREADS; ++i)threads[i]->join(); }
5. Comparison: creation of a thread whose ownership is passed to another object/method.
void foo() { thread thrd* = new thread(&bar); manager.owns(thread); } void foo() { thread_ref thrd = create_thread(&bar); manager.owns(thrd); }
6. Comparison: creation of a thread whose ownership is shared between multiple objects.
void foo() { boost::shared_ptr<thread> thrd(new thread(&bar)); manager1.add(thrd); manager2.add(thrd); } void foo() { thread_ref thrd = create_thread(&bar); manager1.add(thrd); manager2.add(thrd); }
This shows the usage patterns being nearly identical in complexity for both designs. The only actual added complexity occurs because of the use of operator new in (4), (5), and (6); and the use of std::auto_ptr and boost::shared_ptr in (4) and (6) respectively. However, that's not really much added complexity, and C++ programmers are used to using these idioms anyway. Some may dislike the presence of operator new in user code, but this can be eliminated by proper design of higher level concepts, such as the boost::thread_group class that simplifies example (4) down to:
void foo() { thread_group threads; for (int i=0; i<NUM_THREADS; ++i) threads.create_thread(&bar); threads.join_all(); }
So ease of use is really a wash and not much help in picking a design.
So what about performance? Looking at the above code examples, we can analyze the theoretical impact to performance that both designs have. For (1) we can see that platforms that don't have a ref-counted native thread type (POSIX, for instance) will be impacted by a thread_ref design. Even if the native thread type is ref-counted there may be an impact if more state information has to be maintained for concepts foreign to the native API, such as clean up stacks for Win32 implementations. For (2) and (3) the performance impact will be identical to (1). For (4) things get a little more interesting and we find that theoretically at least the thread_ref may perform faster since the thread design requires dynamic memory allocation/deallocation. However, in practice there may be dynamic allocation for the thread_ref design as well, it will just be hidden from the user. As long as the implementation has to do dynamic allocations the thread_ref loses again because of the reference management. For (5) we see the same impact as we do for (4). For (6) we still have a possible impact to the thread design because of dynamic allocation but thread_ref no longer suffers because of its reference management, and in fact, theoretically at least, the thread_ref may do a better job of managing the references. All of this indicates that thread wins for (1), (2) and (3); with (4) and (5) the winner depending on the implementation and the platform but with the thread design probably having a better chance; and with (6) it will again depend on the implementation and platform but this time we favor thread_ref slightly. Given all of this it's a narrow margin, but the thread design prevails.
Given this analysis, and the fact that noncopyable objects for system resources are the normal designs that C++ programmers are used to dealing with, the Boost.Threads library has gone with a noncopyable design.
Rationale for not providing Event Variables
Event variables
are simply far too error-prone. boost::condition variables are a much safer alternative. [Note that Graphical User Interface events are a different concept, and are not what is being discussed here.]
Event variables were one of the first synchronization primitives. They are still used today, for example, in the native Windows multithreading API. Yet both respected computer science researchers and experienced multithreading practitioners believe event variables are so inherently error-prone that they should never be used, and thus should not be part of a multithreading library.
Per Brinch Hansen [Hansen73] analyzed event variables in some detail, pointing out [emphasis his] that "event operations force the programmer to be aware of the relative speeds of the sending and receiving processes". His summary:
We must therefore conclude that event variables of the previous type are impractical for system design. The effect of an interaction between two processes must be independent of the speed at which it is carried out.
Experienced programmers using the Windows platform today report that event variables are a continuing source of errors, even after previous bad experiences caused them to be very careful in their use of event variables. Overt problems can be avoided, for example, by teaming the event variable with a mutex, but that may just convert a race condition into another problem, such as excessive resource use. One of the most distressing aspects of the experience reports is the claim that many defects are latent. That is, the programs appear to work correctly, but contain hidden timing dependencies which will cause them to fail when environmental factors or usage patterns change, altering relative thread timings.
The decision to exclude event variables from Boost.Threads has been surprising to some Windows programmers. They have written programs which work using event variables, and wonder what the problem is. It seems similar to the "goto considered harmful" controversy of 30 years ago. It isn't that events, like gotos, can't be made to work, but rather that virtually all programs using alternatives will be easier to write, debug, read, maintain, and will be less likely to contain latent defects.
[Rationale provided by Beman Dawes]
Reference
Reference
Header <boost/thread/barrier.hpp>
namespace
boost { class barrier; }
Class barrier
Class barrier -- An object of class barrier is a synchronization primitive used to cause a set of threads to wait until they each perform a certain function or each reach a particular point in their execution.
boost::barrier
class
barrier : private boost::noncopyable // Exposition only { public: // construct/copy/destruct barrier(size_t); ~barrier();

// waiting
bool
wait
(); };
Description
Description
When a barrier is created, it is initialized with a thread count N. The first N-1 calls to wait() will all cause their threads to be blocked. The Nth call to wait() will allow all of the waiting threads, including the Nth thread, to be placed in a ready state. The Nth call will also "reset" the barrier such that, if an additional N+1th call is made to wait(), it will be as though this were the first call to wait(); in other words, the N+1th to 2N-1th calls to wait() will cause their threads to be blocked, and the 2Nth call to wait() will allow all of the waiting threads, including the 2Nth thread, to be placed in a ready state and reset the barrier. This functionality allows the same set of N threads to re-use a barrier object to synchronize their execution at multiple points during their execution.
See Glossary for definitions of thread states blocked and ready. Note that "waiting" is a synonym for blocked.
barrier construct/copy/destruct
barrier
construct/copy/destruct
1.
barrier(size_t count);
Effects
Constructs a barrier object that will cause count threads to block on a call to wait().
2.
~barrier();
Effects
Destroys *this. If threads are still executing their wait() operations, the behavior for these threads is undefined.
barrier waiting
barrier
waiting
1.
bool
wait();
Effects
Wait until N threads call wait(), where N equals the count provided to the constructor for the barrier object.
Note
that if the barrier is destroyed before wait() can return, the behavior is undefined.
Returns
Exactly one of the N threads will receive a return value of true, the others will receive a value of false. Precisely which thread receives the return value of true will be implementation-defined. Applications can use this value to designate one thread as a leader that will take a certain action, and the other threads emerging from the barrier can wait for that action to take place.
Header <boost/thread/condition.hpp>
namespace
boost { class condition; }
Class condition
Class condition -- An object of class condition is a synchronization primitive used to cause a thread to wait until a particular shared-data condition (or time) is met.
boost::condition
class
condition : private boost::noncopyable // Exposition only { public: // construct/copy/destruct condition(); ~condition();

// notification
void
notify_one
(); void notify_all();

// waiting
template
<typename ScopedLock> void wait(ScopedLock&); template<typename ScopedLock, typename Pred> void wait(ScopedLock&, Pred); template<typename ScopedLock> bool timed_wait(ScopedLock&, const boost::xtime&); template<typename ScopedLock, typename Pred> bool timed_wait(ScopedLock&, Pred); };
Description
Description
A condition object is always used in conjunction with a mutex object (an object whose type is a model of a Mutex or one of its refinements). The mutex object must be locked prior to waiting on the condition, which is verified by passing a lock object (an object whose type is a model of Lock or one of its refinements) to the condition object's wait functions. Upon blocking on the condition object, the thread unlocks the mutex object. When the thread returns from a call to one of the condition object's wait functions the mutex object is again locked. The tricky unlock/lock sequence is performed automatically by the condition object's wait functions.
The condition type is often used to implement the Monitor Object and other important patterns (see [SchmidtStalRohnertBuschmann] and [Hoare74]). Monitors are one of the most important patterns for creating reliable multithreaded programs.
See Glossary for definitions of thread states blocked and ready. Note that "waiting" is a synonym for blocked.
condition construct/copy/destruct
condition
construct/copy/destruct
1.
condition();
Effects
Constructs a condition object.
2.
~condition();
Effects
Destroys *this.
condition notification
condition
notification
1.
void
notify_one();
Effects
If there is a thread waiting on *this, change that thread's state to ready. Otherwise there is no effect.
Notes
If more than one thread is waiting on *this, it is unspecified which is made ready. After returning to a ready state the notified thread must still acquire the mutex again (which occurs within the call to one of the condition object's wait functions.)
2.
void
notify_all();
Effects
Change the state of all threads waiting on *this to ready. If there are no waiting threads, notify_all() has no effect.
condition waiting
condition
waiting
1.
template
<typename ScopedLock> void wait(ScopedLock& lock);
Requires
ScopedLock
meets the ScopedLock requirements.
Effects
Releases the lock on the mutex object associated with lock, blocks the current thread of execution until readied by a call to this->notify_one() or this->notify_all(), and then reacquires the lock.
Throws
lock_error
if !lock.locked()
2.
template
<typename ScopedLock, typename Pred> void wait(ScopedLock& lock, Pred pred);
Requires
ScopedLock
meets the ScopedLock requirements and the return from pred() is convertible to bool.
Effects
As if: while (!pred()) wait(lock)
Throws
lock_error
if !lock.locked()
3.
template
<typename ScopedLock> bool timed_wait(ScopedLock& lock, const boost::xtime& xt);
Requires
ScopedLock
meets the ScopedLock requirements.
Effects
Releases the lock on the mutex object associated with lock, blocks the current thread of execution until readied by a call to this->notify_one() or this->notify_all(), or until time xt is reached, and then reacquires the lock.
Returns
false
if time xt is reached, otherwise true.
Throws
lock_error
if !lock.locked()
4.
template
<typename ScopedLock, typename Pred> bool timed_wait(ScopedLock& lock, Pred pred);
Requires
ScopedLock
meets the ScopedLock requirements and the return from pred() is convertible to bool.
Effects
As if: while (!pred()) { if (!timed_wait(lock, xt)) return false; } return true;
Returns
false
if xt is reached, otherwise true.
Throws
lock_error
if !lock.locked()
Header <boost/thread/exceptions.hpp>
namespace
boost { class lock_error; class thread_resource_error; }
Class lock_error
Class lock_error -- The lock_error class defines an exception type thrown to indicate a locking related error has been detected.
boost::lock_error
class
lock_error : public std::logical_error { public: // construct/copy/destruct lock_error(); };
Description
Description
Examples of errors indicated by a lock_error exception include a lock operation which can be determined to result in a deadlock, or unlock operations attempted by a thread that does not own the lock.
lock_error construct/copy/destruct
lock_error
construct/copy/destruct
1.
lock_error();
Effects
Constructs a lock_error object.
Class thread_resource_error
Class thread_resource_error -- The thread_resource_error class defines an exception type that is thrown by constructors in the Boost.Threads library when thread-related resources can not be acquired.
boost::thread_resource_error
class
thread_resource_error : public std::runtime_error { public: // construct/copy/destruct thread_resource_error(); };
Description
Description
thread_resource_error
is used only when thread-related resources cannot be acquired; memory allocation failures are indicated by std::bad_alloc.
thread_resource_error construct/copy/destruct
thread_resource_error
construct/copy/destruct
1.
thread_resource_error();
Effects
Constructs a thread_resource_error object.
Header <boost/thread/mutex.hpp>
namespace
boost { class mutex; class try_mutex; class timed_mutex; }
Class mutex
Class mutex -- The mutex class is a model of the Mutex concept.
boost::mutex
class
mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock;

// construct/copy/destruct
mutex
(); ~mutex(); };
Description
Description
The mutex class is a model of the Mutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see try_mutex and timed_mutex.
For Recursive locking mechanics, see recursive_mutex, recursive_try_mutex, and recursive_timed_mutex.
The mutex class supplies the following typedef, which models the specified locking strategy:

Lock Name
Lock Concept
scoped_lock
ScopedLock

The mutex class uses an Unspecified locking strategy, so attempts to recursively lock a mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all mutex models in Boost.Threads, mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
mutex construct/copy/destruct
mutex
construct/copy/destruct
1.
mutex();
Effects
Constructs a mutex object.
Postconditions
*this
is in an unlocked state.
2.
~mutex();
Effects
Destroys a mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class try_mutex
Class try_mutex -- The try_mutex class is a model of the TryMutex concept.
boost::try_mutex
class
try_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock; typedef implementation-defined scoped_try_lock;

// construct/copy/destruct
try_mutex
(); ~try_mutex(); };
Description
Description
The try_mutex class is a model of the TryMutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see mutex and timed_mutex.
For Recursive locking mechanics, see recursive_mutex, recursive_try_mutex, and recursive_timed_mutex.
The try_mutex class supplies the following typedefs, which model the specified locking strategies:

Lock Name
Lock Concept
scoped_lock
ScopedLock
scoped_try_lock
ScopedTryLock

The try_mutex class uses an Unspecified locking strategy, so attempts to recursively lock a try_mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all mutex models in Boost.Threads, try_mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
try_mutex construct/copy/destruct
try_mutex
construct/copy/destruct
1.
try_mutex();
Effects
Constructs a try_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~try_mutex();
Effects
Destroys a try_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class timed_mutex
Class timed_mutex -- The timed_mutex class is a model of the TimedMutex concept.
boost::timed_mutex
class
timed_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock; typedef implementation-defined scoped_try_lock; typedef implementation-defined scoped_timed_lock;

// construct/copy/destruct
timed_mutex
(); ~timed_mutex(); };
Description
Description
The timed_mutex class is a model of the TimedMutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see mutex and try_mutex.
For Recursive locking mechanics, see recursive_mutex, recursive_try_mutex, and recursive_timed_mutex.
The timed_mutex class supplies the following typedefs, which model the specified locking strategies:

Lock Name
Lock Concept
scoped_lock
ScopedLock
scoped_try_lock
ScopedTryLock
scoped_timed_lock
ScopedTimedLock

The timed_mutex class uses an Unspecified locking strategy, so attempts to recursively lock a timed_mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all mutex models in Boost.Threads, timed_mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
timed_mutex construct/copy/destruct
timed_mutex
construct/copy/destruct
1.
timed_mutex();
Effects
Constructs a timed_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~timed_mutex();
Effects
Destroys a timed_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Header <boost/thread/once.hpp>
BOOST_ONCE_INIT
namespace
boost { typedef implementation-defined once_flag; // The call_once function and once_flag type (statically initialized to BOOST_ONCE_INIT) can be used to run a routine exactly once. This can be used to initialize data in a thread-safe manner. call_once(void (*func)(), once_flag&); }
Macro BOOST_ONCE_INIT
Macro BOOST_ONCE_INIT -- The call_once function and once_flag type (statically initialized to BOOST_ONCE_INIT) can be used to run a routine exactly once. This can be used to initialize data in a thread-safe manner.
BOOST_ONCE_INIT
BOOST_ONCE_INIT
Description
Description
The implementation-defined macro BOOST_ONCE_INIT is a constant value used to initialize once_flag instances to indicate that the logically associated routine has not been run yet. See call_once for more details.
Function call_once
Function call_once -- The call_once function and once_flag type (statically initialized to BOOST_ONCE_INIT) can be used to run a routine exactly once. This can be used to initialize data in a thread-safe manner.
boost::call_once
call_once(void (*func)() func, once_flag& flag);
Description
Description
Example usage is as follows:
//Example usage: boost::once_flag once = BOOST_ONCE_INIT;

void init() { //... }

void thread_proc() { boost::call_once(&init, once); }
Requires
The function func shall not throw exceptions.
Effects
As if (in an atomic fashion): if (flag == BOOST_ONCE_INIT) func();
Postconditions
flag != BOOST_ONCE_INIT
Header <boost/thread/recursive_mutex.hpp>
namespace
boost { class recursive_mutex; class recursive_try_mutex; class recursive_timed_mutex; }
Class recursive_mutex
Class recursive_mutex -- The recursive_mutex class is a model of the Mutex concept.
boost::recursive_mutex
class
recursive_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock;

// construct/copy/destruct
recursive_mutex
(); ~recursive_mutex(); };
Description
Description
The recursive_mutex class is a model of the Mutex concept. It should be used to synchronize access to shared resources using Recursive locking mechanics.
For classes that model related mutex concepts, see recursive_try_mutex and recursive_timed_mutex.
For Unspecified locking mechanics, see mutex, try_mutex, and timed_mutex.
The recursive_mutex class supplies the following typedef, which models the specified locking strategy:

Table 23. Supported Lock Types

Lock Name
Lock Concept
scoped_lock
ScopedLock

The recursive_mutex class uses a Recursive locking strategy, so attempts to recursively lock a recursive_mutex object succeed and an internal "lock count" is maintained. Attempts to unlock a recursive_mutex object by threads that don't own a lock on it result in undefined behavior.
Like all mutex models in Boost.Threads, recursive_mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
recursive_mutex construct/copy/destruct
recursive_mutex
construct/copy/destruct
1.
recursive_mutex();
Effects
Constructs a recursive_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~recursive_mutex();
Effects
Destroys a recursive_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class recursive_try_mutex
Class recursive_try_mutex -- The recursive_try_mutex class is a model of the TryMutex concept.
boost::recursive_try_mutex
class
recursive_try_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock; typedef implementation-defined scoped_try_lock;

// construct/copy/destruct
recursive_try_mutex
(); ~recursive_try_mutex(); };
Description
Description
The recursive_try_mutex class is a model of the TryMutex concept. It should be used to synchronize access to shared resources using Recursive locking mechanics.
For classes that model related mutex concepts, see recursive_mutex and recursive_timed_mutex.
For Unspecified locking mechanics, see mutex, try_mutex, and timed_mutex.
The recursive_try_mutex class supplies the following typedefs, which model the specified locking strategies:

Table 24. Supported Lock Types

Lock Name
Lock Concept
scoped_lock
ScopedLock
scoped_try_lock
ScopedTryLock

The recursive_try_mutex class uses a Recursive locking strategy, so attempts to recursively lock a recursive_try_mutex object succeed and an internal "lock count" is maintained. Attempts to unlock a recursive_mutex object by threads that don't own a lock on it result in undefined behavior.
Like all mutex models in Boost.Threads, recursive_try_mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
recursive_try_mutex construct/copy/destruct
recursive_try_mutex
construct/copy/destruct
1.
recursive_try_mutex();
Effects
Constructs a recursive_try_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~recursive_try_mutex();
Effects
Destroys a recursive_try_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class recursive_timed_mutex
Class recursive_timed_mutex -- The recursive_timed_mutex class is a model of the TimedMutex concept.
boost::recursive_timed_mutex
class
recursive_timed_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_lock; typedef implementation-defined scoped_try_lock; typedef implementation-defined scoped_timed_lock;

// construct/copy/destruct
recursive_timed_mutex
(); ~recursive_timed_mutex(); };
Description
Description
The recursive_timed_mutex class is a model of the TimedMutex concept. It should be used to synchronize access to shared resources using Recursive locking mechanics.
For classes that model related mutex concepts, see recursive_mutex and recursive_try_mutex.
For Unspecified locking mechanics, see mutex, try_mutex, and timed_mutex.
The recursive_timed_mutex class supplies the following typedefs, which model the specified locking strategies:

Table 25. Supported Lock Types

Lock Name
Lock Concept
scoped_lock
ScopedLock
scoped_try_lock
ScopedTryLock
scoped_timed_lock
ScopedTimedLock

The recursive_timed_mutex class uses a Recursive locking strategy, so attempts to recursively lock a recursive_timed_mutex object succeed and an internal "lock count" is maintained. Attempts to unlock a recursive_mutex object by threads that don't own a lock on it result in undefined behavior.
Like all mutex models in Boost.Threads, recursive_timed_mutex leaves the scheduling policy as Unspecified. Programmers should make no assumptions about the order in which waiting threads acquire a lock.
recursive_timed_mutex construct/copy/destruct
recursive_timed_mutex
construct/copy/destruct
1.
recursive_timed_mutex();
Effects
Constructs a recursive_timed_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~recursive_timed_mutex();
Effects
Destroys a recursive_timed_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Header <boost/thread/read_write_mutex.hpp>
namespace
boost { class read_write_mutex; class try_read_write_mutex; class timed_read_write_mutex; namespace read_write_scheduling_policy { enum read_write_scheduling_policy; } }
Type read_write_scheduling_policy
Type read_write_scheduling_policy -- Specifies the inter-class sheduling policy to use when a set of threads try to obtain different types of locks simultaneously.
boost::read_write_scheduling_policy::read_write_scheduling_policy
enum
read_write_scheduling_policy { writer_priority, reader_priority, alternating_many_reads, alternating_single_read };
Class read_write_mutex
Class read_write_mutex -- The read_write_mutex class is a model of the ReadWriteMutex concept.
boost::read_write_mutex
class
read_write_mutex : private boost::noncopyable, // Exposition only private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_read_write_lock; typedef implementation-defined scoped_read_lock; typedef implementation-defined scoped_write_lock;

// construct/copy/destruct
read_write_mutex
(boost::read_write_scheduling_policy); ~read_write_mutex(); };
Description
Description
The read_write_mutex class is a model of the ReadWriteMutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see try_read_write_mutex and timed_read_write_mutex.
The read_write_mutex class supplies the following typedefs, which model the specified locking strategies:

Lock Name
Lock Concept
scoped_read_write_lock
ScopedReadWriteLock
scoped_read_lock
ScopedLock
scoped_write_lock
ScopedLock

The read_write_mutex class uses an Unspecified locking strategy, so attempts to recursively lock a read_write_mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all read/write mutex models in Boost.Threads, read_write_mutex has two types of scheduling policies, an inter-class sheduling policy between threads trying to obtain different types of locks and an intra-class sheduling policy between threads trying to obtain the same type of lock. The read_write_mutex class allows the programmer to choose what inter-class sheduling policy will be used; however, like all read/write mutex models, read_write_mutex leaves the intra-class sheduling policy as Unspecified.
Note
Self-deadlock is virtually guaranteed if a thread tries to lock the same read_write_mutex multiple times unless all locks are read-locks (but see below)
read_write_mutex construct/copy/destruct
read_write_mutex
construct/copy/destruct
1.
read_write_mutex(boost::read_write_scheduling_policy count);
Effects
Constructs a read_write_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~read_write_mutex();
Effects
Destroys a read_write_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class try_read_write_mutex
Class try_read_write_mutex -- The try_read_write_mutex class is a model of the TryReadWriteMutex concept.
boost::try_read_write_mutex
class
try_read_write_mutex : private boost::noncopyable // Exposition only { public: // types typedef implementation-defined scoped_read_write_lock; typedef implementation-defined scoped_try_read_write_lock; typedef implementation-defined scoped_read_lock; typedef implementation-defined scoped_try_read_lock; typedef implementation-defined scoped_write_lock; typedef implementation-defined scoped_try_write_lock;

// construct/copy/destruct
try_read_write_mutex
(boost::read_write_scheduling_policy); ~try_read_write_mutex(); };
Description
Description
The try_read_write_mutex class is a model of the TryReadWriteMutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see read_write_mutex and timed_read_write_mutex.
The try_read_write_mutex class supplies the following typedefs, which model the specified locking strategies:

Lock Name
Lock Concept
scoped_read_write_lock
ScopedReadWriteLock
scoped_try_read_write_lock
ScopedTryReadWriteLock
scoped_read_lock
ScopedLock
scoped_try_read_lock
ScopedTryLock
scoped_write_lock
ScopedLock
scoped_try_write_lock
ScopedTryLock

The try_read_write_mutex class uses an Unspecified locking strategy, so attempts to recursively lock a try_read_write_mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all read/write mutex models in Boost.Threads, try_read_write_mutex has two types of scheduling policies, an inter-class sheduling policy between threads trying to obtain different types of locks and an intra-class sheduling policy between threads trying to obtain the same type of lock. The try_read_write_mutex class allows the programmer to choose what inter-class sheduling policy will be used; however, like all read/write mutex models, try_read_write_mutex leaves the intra-class sheduling policy as Unspecified.
Note
Self-deadlock is virtually guaranteed if a thread tries to lock the same try_read_write_mutex multiple times unless all locks are read-locks (but see below)
try_read_write_mutex construct/copy/destruct
try_read_write_mutex
construct/copy/destruct
1.
try_read_write_mutex(boost::read_write_scheduling_policy count);
Effects
Constructs a try_read_write_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~try_read_write_mutex();
Effects
Destroys a try_read_write_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Class timed_read_write_mutex
Class timed_read_write_mutex -- The timed_read_write_mutex class is a model of the TimedReadWriteMutex concept.
boost::timed_read_write_mutex
class
timed_read_write_mutex { public: // types typedef implementation-defined scoped_read_write_lock; typedef implementation-defined scoped_try_read_write_lock; typedef implementation-defined scoped_timed_read_write_lock; typedef implementation-defined scoped_read_lock; typedef implementation-defined scoped_try_read_lock; typedef implementation-defined scoped_timed_read_lock; typedef implementation-defined scoped_write_lock; typedef implementation-defined scoped_try_write_lock; typedef implementation-defined scoped_timed_write_lock;

// construct/copy/destruct
timed_read_write_mutex
(boost::read_write_scheduling_policy); ~timed_read_write_mutex(); };
Description
Description
The timed_read_write_mutex class is a model of the TimedReadWriteMutex concept. It should be used to synchronize access to shared resources using Unspecified locking mechanics.
For classes that model related mutex concepts, see read_write_mutex and try_read_write_mutex.
The timed_read_write_mutex class supplies the following typedefs, which model the specified locking strategies:

Lock Name
Lock Concept
scoped_read_write_lock
ScopedReadWriteLock
scoped_try_read_write_lock
ScopedTryReadWriteLock
scoped_timed_read_write_lock
ScopedTimedReadWriteLock
scoped_read_lock
ScopedLock
scoped_try_read_lock
ScopedTryLock
scoped_timed_read_lock
ScopedTimedLock
scoped_write_lock
ScopedLock
scoped_try_write_lock
ScopedTryLock
scoped_timed_write_lock
ScopedTimedLock

The timed_read_write_mutex class uses an Unspecified locking strategy, so attempts to recursively lock a timed_read_write_mutex object or attempts to unlock one by threads that don't own a lock on it result in undefined behavior. This strategy allows implementations to be as efficient as possible on any given platform. It is, however, recommended that implementations include debugging support to detect misuse when NDEBUG is not defined.
Like all read/write mutex models in Boost.Threads, timed_read_write_mutex has two types of scheduling policies, an inter-class sheduling policy between threads trying to obtain different types of locks and an intra-class sheduling policy between threads trying to obtain the same type of lock. The timed_read_write_mutex class allows the programmer to choose what inter-class sheduling policy will be used; however, like all read/write mutex models, timed_read_write_mutex leaves the intra-class sheduling policy as Unspecified.
Note
Self-deadlock is virtually guaranteed if a thread tries to lock the same timed_read_write_mutex multiple times unless all locks are read-locks (but see below)
timed_read_write_mutex construct/copy/destruct
timed_read_write_mutex
construct/copy/destruct
1.
timed_read_write_mutex(boost::read_write_scheduling_policy count);
Effects
Constructs a timed_read_write_mutex object.
Postconditions
*this
is in an unlocked state.
2.
~timed_read_write_mutex();
Effects
Destroys a timed_read_write_mutex object.
Requires
*this
is in an unlocked state.
Notes
Danger:
Destruction of a locked mutex is a serious programming error resulting in undefined behavior such as a program crash.
Header <boost/thread/thread.hpp>
namespace
boost { class thread; class thread_group; }
Class thread
Class thread -- The thread class represents threads of execution, and provides the functionality to create and manage threads within the Boost.Threads library. See Glossary for a precise description of thread of execution, and for definitions of threading-related terms and of thread states such as blocked.
boost::thread
class
thread : private boost::noncopyable // Exposition only { public: // construct/copy/destruct thread(); explicit thread(const boost::function0<void>&); ~thread();

// comparison
bool
operator
==
() const; bool operator!=() const;

// modifier
void
join
();

// static
static
void
sleep
(const xtime&); static void yield(); };
Description
Description
A thread of execution has an initial function. For the program's initial thread, the initial function is main(). For other threads, the initial function is operator() of the function object passed to the thread object's constructor.
A thread of execution is said to be "finished" or to have "finished execution" when its initial function returns or is terminated. This includes completion of all thread cleanup handlers, and completion of the normal C++ function return behaviors, such as destruction of automatic storage (stack) objects and releasing any associated implementation resources.
A thread object has an associated state which is either "joinable" or "non-joinable".
Except as described below, the policy used by an implementation of Boost.Threads to schedule transitions between thread states is unspecified.
Note
Just as the lifetime of a file may be different from the lifetime of an iostream object which represents the file, the lifetime of a thread of execution may be different from the thread object which represents the thread of execution. In particular, after a call to join(), the thread of execution will no longer exist even though the thread object continues to exist until the end of its normal lifetime. The converse is also possible; if a thread object is destroyed without join() first having been called, the thread of execution continues until its initial function completes.
thread construct/copy/destruct
thread
construct/copy/destruct
1.
thread();
Effects
Constructs a thread object representing the current thread of execution.
Postconditions
*this
is non-joinable.
Notes
Danger:
*this
is valid only within the current thread.
2.
explicit
thread(const boost::function0<void>& threadfunc);
Effects
Starts a new thread of execution and constructs a thread object representing it. Copies threadfunc (which in turn copies the function object wrapped by threadfunc) to an internal location which persists for the lifetime of the new thread of execution. Calls operator() on the copy of the threadfunc function object in the new thread of execution.
Postconditions
*this
is joinable.
Throws
boost::thread_resource_error
if a new thread of execution cannot be started.
3.
~thread();
Effects
Destroys *this. The actual thread of execution may continue to execute after the thread object has been destroyed.
Notes
If *this is joinable the actual thread of execution becomes "detached". Any resources used by the thread will be reclaimed when the thread of execution completes. To ensure such a thread of execution runs to completion before the thread object is destroyed, call join().
thread comparison
thread
comparison
1.
bool
operator
==( rhs) const;
Requires
The thread is non-terminated or *this is joinable.
Returns
true
if *this and rhs represent the same thread of execution.
2.
bool
operator
!=( rhs) const;
Requires
The thread is non-terminated or *this is joinable.
Returns
!(*this==rhs)
.
thread modifier
thread
modifier
1.
void
join();
Requires
*this
is joinable.
Effects
The current thread of execution blocks until the initial function of the thread of execution represented by *this finishes and all resources are reclaimed.
Notes
If *this == thread() the result is implementation-defined. If the implementation doesn't detect this the result will be deadlock.
thread static
thread
static
1.
static
void
sleep(const xtime& xt);
Effects
The current thread of execution blocks until xt is reached.
2.
static
void
yield();
Effects
The current thread of execution is placed in the ready state.
Notes
Allow the current thread to give up the rest of its time slice (or other scheduling quota) to another thread. Particularly useful in non-preemptive implementations.
Class thread_group
Class thread_group -- The thread_group class provides a container for easy grouping of threads to simplify several common thread creation and management idioms.
boost::thread_group
class
thread_group : private boost::noncopyable // Exposition only { public: // construct/copy/destruct thread_group(); ~thread_group();

// modifier
thread
* create_thread(const boost::function0<void>&); void add_thread(thread* thrd); void remove_thread(thread* thrd); void join_all(); };
Description
Description
thread_group construct/copy/destruct
thread_group
construct/copy/destruct
1.
thread_group();
Effects
Constructs an empty thread_group container.
2.
~thread_group();
Effects
Destroys each contained thread object. Destroys *this.
Notes
Behavior is undefined if another thread references *this during the execution of the destructor.
thread_group modifier
thread_group
modifier
1.
thread
* create_thread(const boost::function0<void>& threadfunc);
Effects
Creates a new thread object that executes threadfunc and adds it to the thread_group container object's list of managed thread objects.
Returns
Pointer to the newly created thread object.
2.
void
add_thread(thread* thrd thrd);
Effects
Adds thrd to the thread_group object's list of managed thread objects. The thrd object must have been allocated via operator new and will be deleted when the group is destroyed.
3.
void
remove_thread(thread* thrd thrd);
Effects
Removes thread from *this's list of managed thread objects.
Throws
???
if thrd is not in *this's list of managed thread objects.
4.
void
join_all();
Effects
Calls join() on each of the managed thread objects.
Header <boost/thread/tss.hpp>
namespace
boost { class thread_specific_ptr; }
Class thread_specific_ptr
Class thread_specific_ptr -- The thread_specific_ptr class defines an interface for using thread specific storage.
boost::thread_specific_ptr
class
thread_specific_ptr : private boost::noncopyable // Exposition only { public: // construct/copy/destruct thread_specific_ptr(); thread_specific_ptr(void (*cleanup)(void*)); ~thread_specific_ptr();

// modifier functions
T* release(); void reset(T* = 0);

// observer functions
T* get() const; T* operator->() const; T& operator*()() const; };
Description
Description
Thread specific storage is data associated with individual threads and is often used to make operations that rely on global data thread-safe.
Template thread_specific_ptr stores a pointer to an object obtained on a thread-by-thread basis and calls a specified cleanup handler on the contained pointer when the thread terminates. The cleanup handlers are called in the reverse order of construction of the thread_specific_ptrs, and for the initial thread are called by the destructor, providing the same ordering guarantees as for normal declarations. Each thread initially stores the null pointer in each thread_specific_ptr instance.
The template thread_specific_ptr is useful in the following cases: •An interface was originally written assuming a single thread of control and it is being ported to a multithreaded environment.•Each thread of control invokes sequences of methods that share data that are physically unique for each thread, but must be logically accessed through a globally visible access point instead of being explicitly passed.
thread_specific_ptr construct/copy/destruct
thread_specific_ptr
construct/copy/destruct
1.
thread_specific_ptr();
Requires
The expression delete get() is well formed.
Effects
A thread-specific data key is allocated and visible to all threads in the process. Upon creation, the value NULL will be associated with the new key in all active threads. A cleanup method is registered with the key that will call delete on the value associated with the key for a thread when it exits. When a thread exits, if a key has a registered cleanup method and the thread has a non-NULL value associated with that key, the value of the key is set to NULL and then the cleanup method is called with the previously associated value as its sole argument. The order in which registered cleanup methods are called when a thread exits is undefined. If after all the cleanup methods have been called for all non-NULL values, there are still some non-NULL values with associated cleanup handlers the result is undefined behavior.
Throws
boost::thread_resource_error
if the necessary resources can not be obtained.
Notes
There may be an implementation specific limit to the number of thread specific storage objects that can be created, and this limit may be small.
Rationale
The most common need for cleanup will be to call delete on the associated value. If other forms of cleanup are required the overloaded constructor should be called instead.
2.
thread_specific_ptr(void (*cleanup)(void*) cleanup);
Effects
A thread-specific data key is allocated and visible to all threads in the process. Upon creation, the value NULL will be associated with the new key in all active threads. The cleanup method is registered with the key and will be called for a thread with the value associated with the key for that thread when it exits. When a thread exits, if a key has a registered cleanup method and the thread has a non-NULL value associated with that key, the value of the key is set to NULL and then the cleanup method is called with the previously associated value as its sole argument. The order in which registered cleanup methods are called when a thread exits is undefined. If after all the cleanup methods have been called for all non-NULL values, there are still some non-NULL values with associated cleanup handlers the result is undefined behavior.
Throws
boost::thread_resource_error
if the necessary resources can not be obtained.
Notes
There may be an implementation specific limit to the number of thread specific storage objects that can be created, and this limit may be small.
Rationale
There is the occasional need to register specialized cleanup methods, or to register no cleanup method at all (done by passing NULL to this constructor.
3.
~thread_specific_ptr();
Effects
Deletes the thread-specific data key allocated by the constructor. The thread-specific data values associated with the key need not be NULL. It is the responsibility of the application to perform any cleanup actions for data associated with the key.
Notes
Does not destroy any data that may be stored in any thread's thread specific storage. For this reason you should not destroy a thread_specific_ptr object until you are certain there are no threads running that have made use of its thread specific storage.
Rationale
Associated data is not cleaned up because registered cleanup methods need to be run in the thread that allocated the associated data to be guarranteed to work correctly. There's no safe way to inject the call into another thread's execution path, making it impossible to call the cleanup methods safely.
thread_specific_ptr modifier functions
thread_specific_ptr
modifier functions
1.
T* release();
Postconditions
*this
holds the null pointer for the current thread.
Returns
this->get()
prior to the call.
Rationale
This method provides a mechanism for the user to relinquish control of the data associated with the thread-specific key.
2.
void
reset(T* p = 0);
Effects
If this->get() != p && this->get() != NULL then call the associated cleanup function.
Postconditions
*this
holds the pointer p for the current thread.
thread_specific_ptr observer functions
thread_specific_ptr
observer functions
1.
T* get() const;
Returns
The object stored in thread specific storage for the current thread for *this.
Notes
Each thread initially returns 0.
2.
T* operator->() const;
Returns
this->get()
.
3.
T& operator*()() const;
Requires
this->get() != 0
Returns
this->get()
.
Header <boost/thread/xtime.hpp>
namespace
boost { enum xtime_clock_types;

struct
xtime
; int xtime_get(xtime*, int); }
Type xtime_clock_types
Type xtime_clock_types -- Specifies the clock type to use when creating an object of type xtime.
boost::xtime_clock_types
enum
xtime_clock_types { TIME_UTC };
Struct xtime
Struct xtime -- An object of type xtime defines a time that is used to perform high-resolution time operations. This is a temporary solution that will be replaced by a more robust time library once available in Boost.
boost::xtime
struct
xtime {

platform-specific-type
sec; };

// creation
int
xtime_get
(xtime*, int);
Description
Description
The xtime type is used to represent a point on some time scale or a duration in time. This type may be proposed for the C standard by Markus Kuhn. Boost.Threads provides only a very minimal implementation of this proposal; it is expected that a full implementation (or some other time library) will be provided in Boost as a separate library, at which time Boost.Threads will deprecate its own implementation.
Note
that the resolution is implementation specific. For many implementations the best resolution of time is far more than one nanosecond, and even when the resolution is reasonably good, the latency of a call to xtime_get() may be significant. For maximum portability, avoid durations of less than one second.
xtime creation
xtime
creation
1.
int
xtime_get(xtime* xtp, int clock_type);
Postconditions
xtp
represents the current point in time as a duration since the epoch specified by clock_type.
Returns
clock_type
if successful, otherwise 0.
Frequently Asked Questions
Frequently Asked Questions
1.
Are lock objects thread safe?
No!
Lock objects are not meant to be shared between threads. They are meant to be short-lived objects created on automatic storage within a code block. Any other usage is just likely to lead to errors and won't really be of actual benefit anyway. Share Mutexes, not Locks. For more information see the rationale behind the design for lock objects.
2.
Why was Boost.Threads modeled after (specific library name)?
It wasn't. Boost.Threads was designed from scratch. Extensive design discussions involved numerous people representing a wide range of experience across many platforms. To ensure portability, the initial implements were done in parallel using POSIX Threads and the Win32 threading API. But the Boost.Threads design is very much in the spirit of C++, and thus doesn't model such C based APIs.
3.
Why wasn't Boost.Threads modeled after (specific library name)?
Existing C++ libraries either seemed dangerous (often failing to take advantage of prior art to reduce errors) or had excessive dependencies on library components unrelated to threading. Existing C libraries couldn't meet our C++ requirements, and were also missing certain features. For instance, the WIN32 thread API lacks condition variables, even though these are critical for the important Monitor pattern [SchmidtStalRohnertBuschmann].
4.
Why do Mutexes have noncopyable semantics?
To ensure that deadlocks don't occur. The only logical form of copy would be to use some sort of shallow copy semantics in which multiple mutex objects could refer to the same mutex state. This means that if ObjA has a mutex object as part of its state and ObjB is copy constructed from it, then when ObjB::foo() locks the mutex it has effectively locked ObjA as well. This behavior can result in deadlock. Other copy semantics result in similar problems (if you think you can prove this to be wrong then supply us with an alternative and we'll reconsider).
5.
How can you prevent deadlock from occurring when a thread must lock multiple mutexes?
Always lock them in the same order. One easy way of doing this is to use each mutex's address to determine the order in which they are locked. A future Boost.Threads concept may wrap this pattern up in a reusable class.
6.
Don't noncopyable Mutex semantics mean that a class with a mutex member will be noncopyable as well?
No, but what it does mean is that the compiler can't generate a copy constructor and assignment operator, so they will have to be coded explicitly. This is a good thing, however, since the compiler generated operations would not be thread-safe. The following is a simple example of a class with copyable semantics and internal synchronization through a mutex member.
class counter { public: // Doesn't need synchronization since there can be no references to *this // until after it's constructed! explicit counter(int initial_value) : m_value(initial_value) { } // We only need to synchronize other for the same reason we don't have to // synchronize on construction! counter(const counter& other) { boost::mutex::scoped_lock scoped_lock(other.m_mutex); m_value = other.m_value; } // For assignment we need to synchronize both objects! const counter& operator=(const counter& other) { if (this == &other) return *this; boost::mutex::scoped_lock lock1(&m_mutex < &other.m_mutex ? m_mutex : other.m_mutex); boost::mutex::scoped_lock lock2(&m_mutex > &other.m_mutex ? m_mutex : other.m_mutex); m_value = other.m_value; return *this; } int value() const { boost::mutex::scoped_lock scoped_lock(m_mutex); return m_value; } int increment() { boost::mutex::scoped_lock scoped_lock(m_mutex); return ++m_value; } private: mutable boost::mutex m_mutex; int m_value; };
7.
How can you lock a Mutex member in a const member function, in order to implement the Monitor Pattern?
The Monitor Pattern [SchmidtStalRohnertBuschmann] mutex should simply be declared as mutable. See the example code above. The internal state of mutex types could have been made mutable, with all lock calls made via const functions, but this does a poor job of documenting the actual semantics (and in fact would be incorrect since the logical state of a locked mutex clearly differs from the logical state of an unlocked mutex). Declaring a mutex member as mutable clearly documents the intended semantics.
8.
Why supply boost::condition variables rather than event variables?
Condition variables result in user code much less prone to race conditions than event variables. See the section called “Rationale for not providing Event Variables” for analysis. Also see [Hoare74] and [SchmidtStalRohnertBuschmann].
9.
Why isn't thread cancellation or termination provided?
There's a valid need for thread termination, so at some point Boost.Threads probably will include it, but only after we can find a truly safe (and portable) mechanism for this concept.
10.
Is it safe for threads to share automatic storage duration (stack) objects via pointers or references?
Only if you can guarantee that the lifetime of the stack object will not end while other threads might still access the object. Thus the safest practice is to avoid sharing stack objects, particularly in designs where threads are created and destroyed dynamically. Restrict sharing of stack objects to simple designs with very clear and unchanging function and thread lifetimes. (Suggested by Darryl Green).
11.
Why has class semaphore disappeared?
Semaphore was removed as too error prone. The same effect can be achieved with greater safety by the combination of a mutex and a condition variable.
Configuration
Configuration
Boost.Threads
uses several configuration macros in <boost/config.hpp>, as well as configuration macros meant to be supplied by the application. These macros are documented here.
Library Defined Public Macros
These macros are defined by Boost.Threads but are expected to be used by application code.

Macro
Meaning
BOOST_HAS_THREADS
Indicates that threading support is available. This means both that there is a platform specific implementation for Boost.Threads and that threading support has been enabled in a platform specific manner. For instance, on the Win32 platform there's an implementation for Boost.Threads but unless the program is compiled against one of the multithreading runtimes (often determined by the compiler predefining the macro _MT) the BOOST_HAS_THREADS macro remains undefined.

Library Defined Implementation Macros
These macros are defined by Boost.Threads and are implementation details of interest only to implementors.

Macro
Meaning
BOOST_HAS_WINTHREADS
Indicates that the platform has the Microsoft Win32 threading libraries, and that they should be used to implement Boost.Threads.
BOOST_HAS_PTHREADS
Indicates that the platform has the POSIX pthreads libraries, and that they should be used to implement Boost.Threads.
BOOST_HAS_FTIME
Indicates that the implementation should use GetSystemTimeAsFileTime() and the FILETIME type to calculate the current time. This is an implementation detail used by boost::detail::getcurtime().
BOOST_HAS_GETTTIMEOFDAY
Indicates that the implementation should use gettimeofday() to calculate the current time. This is an implementation detail used by boost::detail::getcurtime().

Build
Build
How you build the Boost.Threads libraries, and how you build your own applications that use those libraries, are some of the most frequently asked questions. Build processes are difficult to deal with in a portable manner. That's one reason why Boost.Threads makes use of Boost.Build. In general you should refer to the documentation for Boost.Build. This document will only supply you with some simple usage examples for how to use bjam to build and test Boost.Threads. In addition, this document will try to explain the build requirements so that users may create their own build processes (for instance, create an IDE specific project), both for building and testing Boost.Threads, as well as for building their own projects using Boost.Threads.
Building the Boost.Threads Libraries
To build the Boost.Threads libraries using Boost.Build, simply change to the directory boost_root/libs/thread/build and execute the command: bjam -sTOOLS=toolset This will create the debug and the release builds of the Boost.Threads library. Note Invoking the above command in boost_root will build all of the Boost distribution, including Boost.Threads.
The Jamfile supplied with Boost.Threads produces a dynamic link library named boost_thread{build-specific-tags}.{extension}, where the build-specific tags indicate the toolset used to build the library, whether it's a debug or release build, what version of Boost was used, etc.; and the extension is the appropriate extension for a dynamic link library for the platform for which Boost.Threads is being built. For instance, a debug library built for Win32 with VC++ 7.1 using Boost 1.31 would be named boost_thread-vc71-mt-gd-1_31.dll.
The source files that are used to create the Boost.Threads library are all of the *.cpp files found in boost_root/libs/thread/src. These need to be built with the compiler's and linker's multi-threading support enabled. If you want to create your own build solution you'll have to follow these same guidelines. One of the most frequently reported problems when trying to do this occurs from not enabling the compiler's and linker's support for multi-threading.
Testing the Boost.Threads Libraries
To test the Boost.Threads libraries using Boost.Build, simply change to the directory boost_root/libs/thread/test and execute the command: bjam -sTOOLS=toolset test
Implementation Notes
Implementation Notes
Win32
In the current Win32 implementation, creating a boost::thread object during dll initialization will result in deadlock because the thread class constructor causes the current thread to wait on the thread that is being created until it signals that it has finished its initialization, and, as stated in the MSDN Library, "DllMain" article, "Remarks" section, "Because DLL notifications are serialized, entry-point functions should not attempt to communicate with other threads or processes. Deadlocks may occur as a result." (Also see "Under the Hood", January 1996 for a more detailed discussion of this issue).
The following non-exhaustive list details some of the situations that should be avoided until this issue can be addressed: •Creating a boost::thread object in DllMain() or in any function called by it.•Creating a boost::thread object in the constructor of a global static object or in any function called by one.•Creating a boost::thread object in MFC's CWinApp::InitInstance() function or in any function called by it.•Creating a boost::thread object in the function pointed to by MFC's _pRawDllMain function pointer or in any function called by it.
Release Notes
Release Notes
Boost 1.32.0
Documentation converted to BoostBook
The documentation was converted to BoostBook format, and a number of errors and inconsistencies were fixed in the process. Since this was a fairly large task, there are likely to be more errors and inconsistencies remaining. If you find any, please report them!
Statically-link build option added
The option to link Boost.Threads as a static library has been added (with some limitations on Win32 platforms). This feature was originally removed from an earlier version of Boost because boost::thread_specific_ptr required that Boost.Threads be dynamically linked in order for its cleanup functionality to work on Win32 platforms. Because this limitation never applied to non-Win32 platforms, because significant progress has been made in removing the limitation on Win32 platforms (many thanks to Aaron LaFramboise and Roland Scwarz!), and because the lack of static linking is one of the most common complaints of Boost.Threads users, this decision was reversed.
On non-Win32 platforms: To choose the dynamically linked version of Boost.Threads using Boost's auto-linking feature, #define BOOST_THREAD_USE_DLL; to choose the statically linked version, #define BOOST_THREAD_USE_LIB. If neither symbols is #defined, the default will be chosen. Currently the default is the statically linked version.
On Win32 platforms using VC++: Use the same #defines as for non-Win32 platforms (BOOST_THREAD_USE_DLL and BOOST_THREAD_USE_LIB). If neither is #defined, the default will be chosen. Currently the default is the statically linked version if the VC++ run-time library is set to "Multi-threaded" or "Multi-threaded Debug", and the dynamically linked version if the VC++ run-time library is set to "Multi-threaded DLL" or "Multi-threaded Debug DLL".
On Win32 platforms using compilers other than VC++: Use the same #defines as for non-Win32 platforms (BOOST_THREAD_USE_DLL and BOOST_THREAD_USE_LIB). If neither is #defined, the default will be chosen. Currently the default is the dynamically linked version because it has not yet been possible to implement automatic tss cleanup in the statically linked version for compilers other than VC++, although it is hoped that this will be possible in a future version of Boost.Threads.

Note for advanced users: Boost.Threads provides several "hook" functions to allow users to experiment with the statically linked version on Win32 with compilers other than VC++. These functions are on_process_enter(), on_process_exit(), on_thread_enter(), and on_thread_exit(), and are defined in tls_hooks.cpp. See the comments in that file for more information.
Barrier functionality added
A new class, boost::barrier, was added.
Read/write mutex functionality added
New classes, boost::read_write_mutex, boost::try_read_write_mutex, and boost::timed_read_write_mutex were added.

Note
Since the read/write mutex and related classes are new, both interface and implementation are liable to change in future releases of Boost.Threads. The lock concepts and lock promotion in particular are still under discussion and very likely to change.
Thread-specific pointer functionality changed
The boost::thread_specific_ptr constructor now takes an optional pointer to a cleanup function that is called to release the thread-specific data that is being pointed to by boost::thread_specific_ptr objects.
Fixed: the number of available thread-specific storage "slots" is too small on some platforms.
Fixed: thread_specific_ptr::reset() doesn't check error returned by tss::set() (the tss::set() function now throws if it fails instead of returning an error code).
Fixed: calling boost::thread_specific_ptr::reset() or boost::thread_specific_ptr::release() causes double-delete: once when boost::thread_specific_ptr::reset() or boost::thread_specific_ptr::release() is called and once when boost::thread_specific_ptr::~thread_specific_ptr() is called.
Mutex implementation changed for Win32
On Win32, boost::mutex, boost::try_mutex, boost::recursive_mutex, and boost::recursive_try_mutex now use a Win32 critical section whenever possible; otherwise they use a Win32 mutex. As before, boost::timed_mutex and boost::recursive_timed_mutex use a Win32 mutex.
Windows CE support improved
Minor changes were made to make Boost.Threads work on Windows CE.
Glossary
Definitions are given in terms of the C++ Standard [ISO98]. References to the standard are in the form [1.2.3/4], which represents the section number, with the paragraph number following the "/".
Because the definitions are written in something akin to "standardese", they can be difficult to understand. The intent isn't to confuse, but rather to clarify the additional requirements Boost.Threads places on a C++ implementation as defined by the C++ Standard.
Acknowledgements
This document was originally written by Beman Dawes, and then much improved by the incorporation of comments from William Kempf, who now maintains the contents.
The visibility rules are based on [Butenhof97].
Thread
Thread is short for "thread of execution". A thread of execution is an execution environment [1.9/7] within the execution environment of a C++ program [1.9]. The main() function [3.6.1] of the program is the initial function of the initial thread. A program in a multithreading environment always has an initial thread even if the program explicitly creates no additional threads.
Unless otherwise specified, each thread shares all aspects of its execution environment with other threads in the program. Shared aspects of the execution environment include, but are not limited to, the following:
•
Static storage duration (static, extern) objects [3.7.1].
•
Dynamic storage duration (heap) objects [3.7.3]. Thus each memory allocation will return a unique addresses, regardless of the thread making the allocation request.
•
Automatic storage duration (stack) objects [3.7.2] accessed via pointer or reference from another thread.
•
Resources provided by the operating system. For example, files.
•
The program itself. In other words, each thread is executing some function of the same program, not a totally different program.
Each thread has its own:
•
Registers and current execution sequence (program counter) [1.9/5].
•
Automatic storage duration (stack) objects [3.7.2].
Thread-safe
A program is thread-safe if it has no race conditions, does not deadlock, and has no priority failures.
Note that thread-safety does not necessarily imply efficiency, and than while some thread-safety violations can be determined statically at compile time, many thread-safety errors can only only be detected at runtime.
Thread State
During the lifetime of a thread, it shall be in one of the following states:
Table 26. Thread States

State
Description
Ready
Ready to run, but waiting for a processor.
Running
Currently executing on a processor. Zero or more threads may be running at any time, with a maximum equal to the number of processors.
Blocked
Waiting for some resource other than a processor which is not currently available, or for the completion of calls to library functions [1.9/6]. The term "waiting" is synonymous with "blocked"
Terminated
Finished execution but not yet detached or joined.

Thread state transitions shall occur only as specified:
Table 27. Thread States Transitions

From
To
Cause
[none]
Ready
Thread is created by a call to a library function. In the case of the initial thread, creation is implicit and occurs during the startup of the main() function [3.6.1].
Ready
Running
Processor becomes available.
Running
Ready
Thread preempted.
Running
Blocked
Thread calls a library function which waits for a resource or for the completion of I/O.
Running
Terminated
Thread returns from its initial function, calls a thread termination library function, or is canceled by some other thread calling a thread termination library function.
Blocked
Ready
The resource being waited for becomes available, or the blocking library function completes.
Terminated
[none]
Thread is detached or joined by some other thread calling the appropriate library function, or by program termination [3.6.3].

[Note: if a suspend() function is added to the threading library, additional transitions to the blocked state will have to be added to the above table.]
Race Condition
A race condition is what occurs when multiple threads read from and write to the same memory without proper synchronization, resulting in an incorrect value being read or written. The result of a race condition may be a bit pattern which isn't even a valid value for the data type. A race condition results in undefined behavior [1.3.12].
Race conditions can be prevented by serializing memory access using the tools provided by Boost.Threads.
Deadlock
Deadlock is an execution state where for some set of threads, each thread in the set is blocked waiting for some action by one of the other threads in the set. Since each is waiting on the others, none will ever become ready again.
Starvation
The condition in which a thread is not making sufficient progress in its work during a given time interval.
Priority Failure
A priority failure (such as priority inversion or infinite overtaking) occurs when threads are executed in such a sequence that required work is not performed in time to be useful.
Undefined Behavior
The result of certain operations in Boost.Threads is undefined; this means that those operations can invoke almost any behavior when they are executed.
An operation whose behavior is undefined can work "correctly" in some implementations (i.e., do what the programmer thought it would do), while in other implementations it may exhibit almost any "incorrect" behavior--such as returning an invalid value, throwing an exception, generating an access violation, or terminating the process.
Executing a statement whose behavior is undefined is a programming error.
Memory Visibility
An address [1.7] shall always point to the same memory byte, regardless of the thread or processor dereferencing the address.
An object [1.8, 1.9] is accessible from multiple threads if it is of static storage duration (static, extern) [3.7.1], or if a pointer or reference to it is explicitly or implicitly dereferenced in multiple threads.
For an object accessible from multiple threads, the value of the object accessed from one thread may be indeterminate or different from the value accessed from another thread, except under the conditions specified in the following table. For the same row of the table, the value of an object accessible at the indicated sequence point in thread A will be determinate and the same if accessed at or after the indicated sequence point in thread B, provided the object is not otherwise modified. In the table, the "sequence point at a call" is the sequence point after the evaluation of all function arguments [1.9/17], while the "sequence point after a call" is the sequence point after the copying of the returned value... [1.9/17].
Table 28. Memory Visibility

Thread A
Thread B
The sequence point at a call to a library thread-creation function.
The first sequence point of the initial function in the new thread created by the Thread A call.
The sequence point at a call to a library function which locks a mutex, directly or by waiting for a condition variable.
The sequence point after a call to a library function which unlocks the same mutex.
The last sequence point before thread termination.
The sequence point after a call to a library function which joins the terminated thread.
The sequence point at a call to a library function which signals or broadcasts a condition variable.
The sequence point after the call to the library function which was waiting on that same condition variable or signal.

The architecture of the execution environment and the observable behavior of the abstract machine [1.9] shall be the same on all processors.
The latitude granted by the C++ standard for an implementation to alter the definition of observable behavior of the abstract machine to include additional library I/O functions [1.9/6] is extended to include threading library functions.
When an exception is thrown and there is no matching exception handler in the same thread, behavior is undefined. The preferred behavior is the same as when there is no matching exception handler in a program [15.3/9]. That is, terminate() is called, and it is implementation-defined whether or not the stack is unwound.
Acknowledgements
Acknowledgements
William E. Kempf was the architect, designer, and implementor of Boost.Threads.
Mac OS Carbon implementation written by Mac Murrett.
Dave Moore provided initial submissions and further comments on the barrier , thread_pool , read_write_mutex , read_write_try_mutex and read_write_timed_mutex classes.
Important contributions were also made by Jeremy Siek (lots of input on the design and on the implementation), Alexander Terekhov (lots of input on the Win32 implementation, especially in regards to boost::condition, as well as a lot of explanation of POSIX behavior), Greg Colvin (lots of input on the design), Paul Mclachlan, Thomas Matelich and Iain Hanson (for help in trying to get the build to work on other platforms), and Kevin S. Van Horn (for several updates/corrections to the documentation).
Mike Glassford finished changes to Boost.Threads that were begun by William Kempf and moved them into the main CVS branch. He also addressed a number of issues that were brought up on the Boost developer's mailing list and provided some additions and changes to the read_write_mutex and related classes.
The documentation was written by William E. Kempf. Beman Dawes provided additional documentation material and editing. Mike Glassford finished William Kempf's conversion of the documentation to BoostBook format and added a number of new sections.
Discussions on the boost.org mailing list were essential in the development of Boost.Threads . As of August 1, 2001, participants included Alan Griffiths, Albrecht Fritzsche, Aleksey Gurtovoy, Alexander Terekhov, Andrew Green, Andy Sawyer, Asger Alstrup Nielsen, Beman Dawes, Bill Klein, Bill Rutiser, Bill Wade, Branko èibej, Brent Verner, Craig Henderson, Csaba Szepesvari, Dale Peakall, Damian Dixon, Dan Nuffer, Darryl Green, Daryle Walker, David Abrahams, David Allan Finch, Dejan Jelovic, Dietmar Kuehl, Douglas Gregor, Duncan Harris, Ed Brey, Eric Swanson, Eugene Karpachov, Fabrice Truillot, Frank Gerlach, Gary Powell, Gernot Neppert, Geurt Vos, Ghazi Ramadan, Greg Colvin, Gregory Seidman, HYS, Iain Hanson, Ian Bruntlett, J Panzer, Jeff Garland, Jeff Paquette, Jens Maurer, Jeremy Siek, Jesse Jones, Joe Gottman, John (EBo) David, John Bandela, John Maddock, John Max Skaller, John Panzer, Jon Jagger , Karl Nelson, Kevlin Henney, KG Chandrasekhar, Levente Farkas, Lie-Quan Lee, Lois Goldthwaite, Luis Pedro Coelho, Marc Girod, Mark A. Borgerding, Mark Rodgers, Marshall Clow, Matthew Austern, Matthew Hurd, Michael D. Crawford, Michael H. Cox , Mike Haller, Miki Jovanovic, Nathan Myers, Paul Moore, Pavel Cisler, Peter Dimov, Petr Kocmid, Philip Nash, Rainer Deyke, Reid Sweatman, Ross Smith, Scott McCaskill, Shalom Reich, Steve Cleary, Steven Kirk, Thomas Holenstein, Thomas Matelich, Trevor Perrin, Valentin Bonnard, Vesa Karvonen, Wayne Miller, and William Kempf.
Apologies for anyone inadvertently missed.
Bibliography
[AndrewsSchnieder83] ACM Computing Surveys. Vol. 15. No. 1. March, 1983. Gregory R. Andrews and Fred B. Schneider. “Concepts and Notations for Concurrent Programming”. Good general background reading. Includes descriptions of Path Expressions, Message Passing, and Remote Procedure Call in addition to the basics
[Boost] The Boost world wide web site. http://www.boost.org. Boost.Threads is one of many Boost libraries. The Boost web site includes a great deal of documentation and general information which applies to all Boost libraries. Current copies of the libraries including documentation and test programs may be downloaded from the web site.
[Hansen73] ACM Computing Surveys. Vol. 5. No. 4. December, 1983. Per Brinch. “Concurrent Programming Concepts”. "This paper describes the evolution of language features for multiprogramming from event queues and semaphores to critical regions and monitors." Includes analysis of why events are considered error-prone. Also noteworthy because of an introductory quotation from Christopher Alexander; Brinch Hansen was years ahead of others in recognizing pattern concepts applied to software, too.
[Butenhof97] Programming with POSIX Threads . David R. Butenhof. Addison-Wesley Copyright © 1997. ISNB: 0-201-63392-2. This is a very readable explanation of threads and how to use them. Many of the insights given apply to all multithreaded programming, not just POSIX Threads
[Hoare74] Communications of the ACM. Vol. 17. No. 10. October, 1974. “Monitors: An Operating System Structuring Concept”. C.A.R. Hoare. 549-557. Hoare and Brinch Hansen's work on Monitors is the basis for reliable multithreading patterns. This is one of the most often referenced papers in all of computer science, and with good reason.
[ISO98] Programming Language C++. ISO/IEC. 14882:1998(E). This is the official C++ Standards document. Available from the ANSI (American National Standards Institute) Electronic Standards Store.
[McDowellHelmbold89] Communications of the ACM. Vol. 21. No. 2. December, 1989. Charles E. McDowell. David P. Helmbold. Debugging Concurrent Programs. Identifies many of the unique failure modes and debugging difficulties associated with concurrent programs.
[SchmidtPyarali] Strategies for Implementing POSIX Condition Variables on Win32. Douglas C. Schmidt and Irfan Pyarali. Department of Computer Science, Washington University, St. Louis, Missouri. Rationale for understanding Boost.Threads condition variables. Note that Alexander Terekhov found some bugs in the implementation given in this article, so pthreads-win32 and Boost.Threads are even more complicated yet.
[SchmidtStalRohnertBuschmann] Pattern-Oriented Architecture Volume 2. Patterns for Concurrent and Networked Objects. POSA2. Douglas C. Schmidt, Michael, Hans Rohnert, and Frank Buschmann. Wiley Copyright © 2000. This is a very good explanation of how to apply several patterns useful for concurrent programming. Among the patterns documented is the Monitor Pattern mentioned frequently in the Boost.Threads documentation.
[Stroustrup] The C++ Programming Language. Special Edition. Addison-Wesley Copyright © 2000. ISBN: 0-201-70073-5. The first book a C++ programmer should own. Note that the 3rd edition (and subsequent editions like the Special Edition) has been rewritten to cover the ISO standard language and library.

Boost.Tribool

Boost.Tribool

Boost.Tribool
Douglas Gregor <dgregor -at- cs.indiana.edu>
Copyright © 2002-2004 Douglas Gregor
Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Introduction
Introduction
The 3-state boolean library contains a single class, boost::logic::tribool, along with support functions and operator overloads that implement 3-state boolean logic.
Tutorial
Tutorial
Basic usage
The tribool class acts like the built-in bool type, but for 3-state boolean logic. The three states are true, false, and indeterminate, where the first two states are equivalent to those of the C++ bool type and the last state represents an unknown boolean value (that may be true or false, we don't know).
The tribool class supports conversion from bool values and literals along with its own indeterminate keyword:
tribool
b(true); b = false; b = indeterminate; tribool b2(b);
tribool
supports conversions to bool for use in conditional statements. The conversion to bool will be true when the value of the tribool is always true, and false otherwise. Consequently, the following idiom may be used to determine which of the three states a tribool currently holds:
tribool
b = some_operation(); if (b) { // b is true } else if (!b) { // b is false } else { // b is indeterminate }
tribool
supports the 3-state logic operators ! (negation), && (AND), and || (OR), with bool and tribool values. For instance:
tribool
x = some_op(); tribool y = some_other_op(); if (x && y) { // both x and y are true } else if (!(x && y)) { // either x or y is false } else { // neither x nor y is false, but we don't know that both are true

if (x || y) { // either x or y is true } }
Similarly, tribool supports 3-state equality comparisons via the operators == and !=. These operators differ from "normal" equality operators in C++ because they return a tribool, because potentially we might not know the result of a comparison (try to compare true and indeterminate). For instance:
tribool
x(true); tribool y(indeterminate);

assert(x == x); // okay, x == x returns true assert(x == true); // okay, can compare tribools and bools
The indeterminate keyword (representing the indeterminate tribool value) doubles as a function to check if the value of a tribool is indeterminate, e.g.,
tribool
x = try_to_do_something_tricky(); if (indeterminate(x)) { // value of x is indeterminate } else { // report success or failure of x }
Renaming the indeterminate state
Users may introduce additional keywords for the indeterminate value in addition to the implementation-supplied indeterminate using the BOOST_TRIBOOL_THIRD_STATE macro. For instance, the following macro instantiation (at the global scope) will introduce the keyword maybe as a synonym for indeterminate (also residing in the boost namespace):
BOOST_TRIBOOL_THIRD_STATE
(maybe) tribool x = maybe; if (maybe(x)) { /* ... */ }
tribool
input/output
tribool
objects may be read from and written to streams by including the boost/logic/tribool_io.hpp header in a manner very similar to bool values. When the boolalpha flag is not set on the input/output stream, the integral values 0, 1, and 2 correspond to tribool values false, true, and indeterminate, respectively. When boolalpha is set on the stream, arbitrary strings can be used to represent the three values, the default being "false", "true", and "indeterminate". For instance:
tribool
x; cin >> x; // Type "0", "1", or "2" to get false, true, or indeterminate cout << boolalpha << x; // Produces "false", "true", or "indeterminate"
tribool
input and output is sensitive to the stream's current locale. The strings associated with false and true values are contained in the standard std::numpunct facet, and the string naming the indeterminate type is contained in the indeterminate_name facet. To replace the name of the indeterminate state, you need to imbue your stream with a local containing a indeterminate_name facet, e.g.:
BOOST_TRIBOOL_THIRD_STATE
(maybe) locale global; locale test_locale(global, new indeterminate_name<char>("maybe")); cout.imbue(test_locale); tribool x(maybe); cout << boolalpha << x << endl; // Prints "maybe"
If you C++ standard library implementation does not support locales, tribool input/output will still work, but you will be unable to customize the strings printed/parsed when boolalpha is set.
Reference
Reference
Header <boost/logic/tribool.hpp>
BOOST_TRIBOOL_THIRD_STATE
(Name)
namespace
boost { namespace logic { class tribool; bool indeterminate(tribool, unspecified = unspecified); tribool operator!(tribool); tribool operator&&(tribool, tribool); tribool operator&&(tribool, bool); tribool operator&&(bool, tribool); tribool operator&&(indeterminate_keyword_t, tribool); tribool operator&&(tribool, indeterminate_keyword_t); tribool operator||(tribool, tribool); tribool operator||(tribool, bool); tribool operator||(bool, tribool); tribool operator||(indeterminate_keyword_t, tribool); tribool operator||(tribool, indeterminate_keyword_t); tribool operator==(tribool, tribool); tribool operator==(tribool, bool); tribool operator==(bool, tribool); tribool operator==(indeterminate_keyword_t, tribool); tribool operator==(tribool, indeterminate_keyword_t); tribool operator!=(tribool, tribool); tribool operator!=(tribool, bool); tribool operator!=(bool, tribool); tribool operator!=(indeterminate_keyword_t, tribool); tribool operator!=(tribool, indeterminate_keyword_t); } }
Class tribool
Class tribool -- A 3-state boolean type.
boost::logic::tribool
class
tribool { public: // construct/copy/destruct tribool(); tribool(bool); tribool(indeterminate_keyword_t);

// public member functions
operator
safe_bool
() const;

enum boost::logic::tribool::@0 value; };
Description
Description
3-state boolean values are either true, false, or indeterminate.
tribool construct/copy/destruct
tribool
construct/copy/destruct
1.
tribool();
Construct a new 3-state boolean value with the value 'false'.
Throws
Will not throw.
2.
tribool(bool value);
Construct a new 3-state boolean value with the given boolean value, which may be true or false .
Throws
Will not throw.
3.
tribool(indeterminate_keyword_t );
Construct a new 3-state boolean value with an indeterminate value.
Throws
Will not throw.
tribool public member functions
tribool
public member functions
1.
operator
safe_bool() const;
Use a 3-state boolean in a boolean context. Will evaluate true in a boolean context only when the 3-state boolean is definitely true.
Returns
true if the 3-state boolean is true, false otherwise
Throws
Will not throw.
Function indeterminate
Function indeterminate -- Keyword and test function for the indeterminate tribool value.
boost::logic::indeterminate
bool
indeterminate(tribool x, unspecified dummy = unspecified);
Description
Description
The indeterminate function has a dual role. It's first role is as a unary function that tells whether the tribool value is in the "indeterminate" state. It's second role is as a keyword representing the indeterminate (just like "true" and "false" represent the true and false states). If you do not like the name "indeterminate", and would prefer to use a different name, see the macro BOOST_TRIBOOL_THIRD_STATE .
Returns
x.value == tribool::indeterminate_value
Throws
Will not throw.
Function operator!
Function operator! -- Computes the logical negation of a tribool.
boost::logic::operator!
tribool
operator
!(tribool x);
Description
Description
Returns
the logical negation of the tribool, according to the table:

!
false
true
true
false
indeterminate
indeterminate

Throws
Will not throw.
Function operator&&
Function operator&& -- Computes the logical conjuction of two tribools.
boost::logic::operator&&
tribool
operator
&&(tribool x, tribool y); tribool operator&&(tribool x, bool y); tribool operator&&(bool x, tribool y); tribool operator&&(indeterminate_keyword_t , tribool x); tribool operator&&(tribool x, indeterminate_keyword_t );
Description
Description
Returns
the result of logically ANDing the two tribool values, according to the following table:

&&
false
true
indeterminate
false
false
false
false
true
false
true
indeterminate
indeterminate
false
indeterminate
indeterminate

Throws
Will not throw.
Function operator||
Function operator|| -- Computes the logical disjunction of two tribools.
boost::logic::operator||
tribool
operator
||(tribool x, tribool y); tribool operator||(tribool x, bool y); tribool operator||(bool x, tribool y); tribool operator||(indeterminate_keyword_t , tribool x); tribool operator||(tribool x, indeterminate_keyword_t );
Description
Description
Returns
the result of logically ORing the two tribool values, according to the following table:

||
false
true
indeterminate
false
false
true
indeterminate
true
true
true
true
indeterminate
indeterminate
true
indeterminate

Throws
Will not throw.
Function operator==
Function operator== -- Compare tribools for equality.
boost::logic::operator==
tribool
operator
==(tribool x, tribool y); tribool operator==(tribool x, bool y); tribool operator==(bool x, tribool y); tribool operator==(indeterminate_keyword_t , tribool x); tribool operator==(tribool x, indeterminate_keyword_t );
Description
Description
Returns
the result of comparing two tribool values, according to the following table:

==
false
true
indeterminate
false
true
false
indeterminate
true
false
true
indeterminate
indeterminate
indeterminate
indeterminate
indeterminate

Throws
Will not throw.
Function operator!=
Function operator!= -- Compare tribools for inequality.
boost::logic::operator!=
tribool
operator
!=(tribool x, tribool y); tribool operator!=(tribool x, bool y); tribool operator!=(bool x, tribool y); tribool operator!=(indeterminate_keyword_t , tribool x); tribool operator!=(tribool x, indeterminate_keyword_t );
Description
Description
Returns
the result of comparing two tribool values for inequality, according to the following table:

!=
false
true
indeterminate
false
false
true
indeterminate
true
true
false
indeterminate
indeterminate
indeterminate
indeterminate
indeterminate

Throws
Will not throw.
Macro BOOST_TRIBOOL_THIRD_STATE
Macro BOOST_TRIBOOL_THIRD_STATE -- Declare a new name for the third state of a tribool.
BOOST_TRIBOOL_THIRD_STATE
BOOST_TRIBOOL_THIRD_STATE(Name)
Description
Description
Use this macro to declare a new name for the third state of a tribool. This state can have any number of new names (in addition to indeterminate ), all of which will be equivalent. The new name will be placed in the namespace in which the macro is expanded.
Example: BOOST_TRIBOOL_THIRD_STATE(true_or_false)
tribool x(true_or_false); // potentially set x if (true_or_false(x)) { // don't know what x is }
Header <boost/logic/tribool_fwd.hpp>
namespace
boost { namespace logic { } }
Header <boost/logic/tribool_io.hpp>
namespace
boost { namespace logic { template<typename CharT> class indeterminate_name; template<typename T> std::basic_string< T > get_default_indeterminate_name();

// Returns the character string "indeterminate".
template
<> std::basic_string< char > get_default_indeterminate_name<char >();

// Returns the wide character string L"indeterminate".
template
<> std::basic_string< wchar_t > get_default_indeterminate_name<wchar_t >(); template<typename CharT, typename Traits> std::basic_ostream< CharT, Traits > & operator<<(std::basic_ostream< CharT, Traits > &, tribool); template<typename CharT, typename Traits> std::basic_istream< CharT, Traits > & operator>>(std::basic_istream< CharT, Traits > &, tribool &); } }
Class template indeterminate_name
Class template indeterminate_name -- A locale facet specifying the name of the indeterminate value of a tribool.
boost::logic::indeterminate_name
template
<typename CharT> class indeterminate_name { public: // types typedef CharT char_type; typedef std::basic_string< CharT > string_type;

// construct/copy/destruct
indeterminate_name
(); indeterminate_name(const string_type &);

// public member functions
string_type name() const;

static
std::locale::id id; };
Description
Description
The facet is used to perform I/O on tribool values when std::boolalpha has been specified. This class template is only available if the C++ standard library implementation supports locales.
indeterminate_name construct/copy/destruct
indeterminate_name
construct/copy/destruct
1.
indeterminate_name();
2.
indeterminate_name(const string_type & name);
indeterminate_name public member functions
indeterminate_name
public member functions
1.
string_type name() const;
Function template get_default_indeterminate_name
Function template get_default_indeterminate_name -- Returns a string containing the default name for the indeterminate value of a tribool with the given character type T.
boost::logic::get_default_indeterminate_name
template
<typename T> std::basic_string< T > get_default_indeterminate_name();
Description
Description
This routine is used by the input and output streaming operators for tribool when there is no locale support or the stream's locale does not contain the indeterminate_name facet.
Function template operator<<
Function template operator<< -- Writes the value of a tribool to a stream.
boost::logic::operator<<
template
<typename CharT, typename Traits> std::basic_ostream< CharT, Traits > & operator<<(std::basic_ostream< CharT, Traits > & out, tribool x);
Description
Description
When the value of x is either true or false , this routine is semantically equivalent to: out << static_cast<bool>(x);
When x has an indeterminate value, it outputs either the integer value 2 (if (out.flags() & std::ios_base::boolalpha) == 0 ) or the name of the indeterminate value. The name of the indeterminate value comes from the indeterminate_name facet (if it is defined in the output stream's locale), or from the get_default_indeterminate_name function (if it is not defined in the locale or if the C++ standard library implementation does not support locales).
Returns
out
Function template operator>>
Function template operator>> -- Reads a tribool value from a stream.
boost::logic::operator>>
template
<typename CharT, typename Traits> std::basic_istream< CharT, Traits > & operator>>(std::basic_istream< CharT, Traits > & in, tribool & x);
Description
Description
When (out.flags() & std::ios_base::boolalpha) == 0 , this function reads a long value from the input stream in and converts that value to a tribool. If that value is 0, x becomes false ; if it is 1, x becomes true ; if it is 2, becomes indetermine ; otherwise, the operation fails (and the fail bit is set on the input stream in ).
When (out.flags() & std::ios_base::boolalpha) != 0 , this function first determines the names of the false, true, and indeterminate values. The false and true names are extracted from the std::numpunct facet of the input stream's locale (if the C++ standard library implementation supports locales), or from the default_false_name and default_true_name functions (if there is no locale support). The indeterminate name is extracted from the appropriate indeterminate_name facet (if it is available in the input stream's locale), or from the get_default_indeterminate_name function (if the C++ standard library implementation does not support locales, or the indeterminate_name facet is not specified for this locale object). The input is then matched to each of these names, and the tribool x is assigned the value corresponding to the longest name that matched. If no name is matched or all names are empty, the operation fails (and the fail bit is set on the input stream in ).
Returns
in
Testsuite
Testsuite
Acceptance tests

Test
Type
Description
If failing...
tribool_test.cpp
run
Test all features of the boost::logic::tribool class.
tribool_rename_test.cpp
run
Test the use of the BOOST_TRIBOOL_THIRD_STATE macro.
tribool_io_test.cpp
run
Test tribool input/output.

Boost.Variant

Boost.Variant

Boost.Variant
Eric Friedman
Itay Maman
Copyright © 2002, 2003 Eric FriedmanItay Maman
Permission to copy, use, sell and distribute this software is granted provided this copyright notice appears in all copies. Permission to modify the code and to distribute modified code is granted provided this copyright notice appears in all copies, and a notice that the code was modified is included with the copyright notice.
This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.
Introduction
Introduction
Abstract
The variant class template is a safe, generic, stack-based discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner. Whereas standard containers such as std::vector may be thought of as "multi-value, single type," variant is "multi-type, single value."
Notable features of boost::variant include:
•
Full value semantics, including adherence to standard overload resolution rules for conversion operations.
•
Compile-time type-safe value visitation via boost::apply_visitor.
•
Run-time checked explicit value retrieval via boost::get.
•
Support for recursive variant types via both boost::make_recursive_variant and boost::recursive_wrapper.
•
Efficient implementation -- stack-based when possible (see the section called “"Never-Empty" Guarantee” for more details).
Motivation
Problem
Many times, during the development of a C++ program, the programmer finds himself in need of manipulating several distinct types in a uniform manner. Indeed, C++ features direct language support for such types through its union keyword:
union { int i; double d; } u; u.d = 3.14; u.i = 3; // overwrites u.d (OK: u.d is a POD type)
C++'s union construct, however, is nearly useless in an object-oriented environment. The construct entered the language primarily as a means for preserving compatibility with C, which supports only POD (Plain Old Data) types, and so does not accept types exhibiting non-trivial construction or destruction:
union { int i; std::string s; // illegal: std::string is not a POD type! } u;
Clearly another approach is required. Typical solutions feature the dynamic-allocation of objects, which are subsequently manipulated through a common base type (often a virtual base class [Hen01] or, more dangerously, a void*). Objects of concrete type may be then retrieved by way of a polymorphic downcast construct (e.g., dynamic_cast, boost::any_cast, etc.).
However, solutions of this sort are highly error-prone, due to the following:
•
Downcast errors cannot be detected at compile-time.
Thus, incorrect usage of downcast constructs will lead to bugs detectable only at run-time.
•
Addition of new concrete types may be ignored.
If a new concrete type is added to the hierarchy, existing downcast code will continue to work as-is, wholly ignoring the new type. Consequently, the programmer must manually locate and modify code at numerous locations, which often results in run-time errors that are difficult to find.
Furthermore, even when properly implemented, these solutions tend to incur a relatively significant abstraction penalty due to the use of the heap, virtual function calls, and polymorphic downcasts.
Solution: A Motivating Example
The boost::variant class template addresses these issues in a safe, straightforward, and efficient manner. The following example demonstrates how the class can be used:
#include "boost/variant.hpp" #include <iostream>

class my_visitor : public boost::static_visitor<int> { public: int operator()(int i) const { return i; }

int operator()(const std::string & str) const { return str.length(); } };

int main() { boost::variant< int, std::string > u("hello world"); std::cout << u; // output: hello world

int result = boost::apply_visitor( my_visitor(), u ); std::cout << result; // output: 11 (i.e., length of "hello world") }
Tutorial
Tutorial
Basic Usage
A discriminated union container on some set of types is defined by instantiating the boost::variant class template with the desired types. These types are called bounded types and are subject to the requirements of the BoundedType concept. Any number of bounded types may be specified, up to some implementation-defined limit (see BOOST_VARIANT_LIMIT_TYPES).
For example, the following declares a discriminated union container on int and std::string:

boost::variant
< int, std::string > v;
By default, a variant default-constructs its first bounded type, so v initially contains int(0). If this is not desired, or if the first bounded type is not default-constructible, a variant can be constructed directly from any value convertible to one of its bounded types. Similarly, a variant can be assigned any value convertible to one of its bounded types, as demonstrated in the following:

v = "hello";
Now v contains a std::string equal to "hello". We can demonstrate this by streaming v to standard output:

std::cout << v << std::endl;
Usually though, we would like to do more with the content of a variant than streaming. Thus, we need some way to access the contained value. There are two ways to accomplish this: apply_visitor, which is safest and very powerful, and get<T>, which is sometimes more convenient to use.
For instance, suppose we wanted to concatenate to the string contained in v. With value retrieval by get, this may be accomplished quite simply, as seen in the following:

std::string& str = boost::get<std::string>(v); str += " world! ";
As desired, the std::string contained by v now is equal to "hello world! ". Again, we can demonstrate this by streaming v to standard output:

std::cout << v << std::endl;
While use of get is perfectly acceptable in this trivial example, get generally suffers from several significant shortcomings. For instance, if we were to write a function accepting a variant<int, std::string>, we would not know whether the passed variant contained an int or a std::string. If we insisted upon continued use of get, we would need to query the variant for its contained type. The following function, which "doubles" the content of the given variant, demonstrates this approach:

void times_two( boost::variant< int, std::string > & operand ) { if ( int* pi = boost::get<int>( &v ) ) *pi *= 2; else if ( std::string* pstr = boost::get<std::string>( &v ) ) *pstr += *pstr; }
However, such code is quite brittle, and without careful attention will likely lead to the introduction of subtle logical errors detectable only at runtime. For instance, consider if we wished to extend times_two to operate on a variant with additional bounded types. Specifically, let's add std::complex<double> to the set. Clearly, we would need to at least change the function declaration:

void times_two( boost::variant< int, std::string, std::complex<double> > & operand ) { // as above...? }
Of course, additional changes are required, for currently if the passed variant in fact contained a std::complex value, times_two would silently return -- without any of the desired side-effects and without any error. In this case, the fix is obvious. But in more complicated programs, it could take considerable time to identify and locate the error in the first place.
Thus, real-world use of variant typically demands an access mechanism more robust than get. For this reason, variant supports compile-time checked visitation via apply_visitor. Visitation requires that the programmer explicitly handle (or ignore) each bounded type. Failure to do so results in a compile-time error.
Visitation of a variant requires a visitor object. The following demonstrates one such implementation of a visitor implementating behavior identical to times_two:

class times_two_visitor : public boost::static_visitor<> { public:

void operator()(int & i) const { i *= 2; }

void operator()(std::string & str) const { str += str; }

};
With the implementation of the above visitor, we can then apply it to v, as seen in the following:

boost::apply_visitor
( times_two_visitor(), v );
As expected, the content of v is now a std::string equal to "hello world! hello world! ". (We'll skip the verification this time.)
In addition to enhanced robustness, visitation provides another important advantage over get: the ability to write generic visitors. For instance, the following visitor will "double" the content of any variant (provided its bounded types each support operator+=):

class times_two_generic : public boost::static_visitor<> { public:

template <typename T> void operator()( T & operand ) const { operand += operand; }

};
Again, apply_visitor sets the wheels in motion:

boost::apply_visitor
( times_two_generic(), v );
While the initial setup costs of visitation may exceed that required for get, the benefits quickly become significant. Before concluding this section, we should explore one last benefit of visitation with apply_visitor: delayed visitation. Namely, a special form of apply_visitor is available that does not immediately apply the given visitor to any variant but rather returns a function object that operates on any variant given to it. This behavior is particularly useful when operating on sequences of variant type, as the following demonstrates:

std::vector< boost::variant<int, std::string> > vec; vec.push_back( 21 ); vec.push_back( "hello " );

times_two_generic visitor; std::for_each( vec.begin(), vec.end() , boost::apply_visitor(visitor) );
Advanced Topics
This section discusses several features of the library often required for advanced uses of variant. Unlike in the above section, each feature presented below is largely independent of the others. Accordingly, this section is not necessarily intended to be read linearly or in its entirety.
Preprocessor macros
While the variant class template's variadic parameter list greatly simplifies use for specific instantiations of the template, it significantly complicates use for generic instantiations. For instance, while it is immediately clear how one might write a function accepting a specific variant instantiation, say variant<int, std::string>, it is less clear how one might write a function accepting any given variant.
Due to the lack of support for true variadic template parameter lists in the C++98 standard, the preprocessor is needed. While the Preprocessor library provides a general and powerful solution, the need to repeat BOOST_VARIANT_LIMIT_TYPES unnecessarily clutters otherwise simple code. Therefore, for common use-cases, this library provides its own macro BOOST_VARIANT_ENUM_PARAMS.
This macro simplifies for the user the process of declaring variant types in function templates or explicit partial specializations of class templates, as shown in the following:

// general cases template <typename T> void some_func(const T &); template <typename T> class some_class;

// function template overload template <BOOST_VARIANT_ENUM_PARAMS(typename T)> void some_func(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &);

// explicit partial specialization template <BOOST_VARIANT_ENUM_PARAMS(typename T)> class some_class< boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >;
Using a type sequence to specify bounded types
While convenient for typical uses, the variant class template's variadic template parameter list is limiting in two significant dimensions. First, due to the lack of support for true variadic template parameter lists in C++, the number of parameters must be limited to some implementation-defined maximum (namely, BOOST_VARIANT_LIMIT_TYPES). Second, the nature of parameter lists in general makes compile-time manipulation of the lists excessively difficult.
To solve these problems, make_variant_over< Sequence > exposes a variant whose bounded types are the elements of Sequence (where Sequence is any type fulfilling the requirements of MPL's Sequence concept). For instance,

typedef mpl::vector< std::string > types_initial; typedef mpl::push_front< types_initial, int >::type types;

boost::make_variant_over
< types >::type v1;

behaves equivalently to

boost::variant
< int, std::string > v2;
Portability
: Unfortunately, due to standard conformance issues in several compilers, make_variant_over is not universally available. On these compilers the library indicates its lack of support for the syntax via the definition of the preprocessor symbol BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT.
Recursive variant types
Recursive types facilitate the construction of complex semantics from simple syntax. For instance, nearly every programmer is familiar with the canonical definition of a linked list implementation, whose simple definition allows sequences of unlimited length:

template <typename T> struct list_node { T data; list_node * next; };
The nature of variant as a generic class template unfortunately precludes the straightforward construction of recursive variant types. Consider the following attempt to construct a structure for simple mathematical expressions:

struct add; struct sub; template <typename OpTag> struct binary_op;

typedef boost::variant< int , binary_op<add> , binary_op<sub> > expression;

template <typename OpTag> struct binary_op { expression left; // variant instantiated here... expression right;

binary_op( const expression & lhs, const expression & rhs ) : left(lhs), right(rhs) { }

}; // ...but binary_op not complete until here!
While well-intentioned, the above approach will not compile because binary_op is still incomplete when the variant type expression is instantiated. Further, the approach suffers from a more significant logical flaw: even if C++ syntax were different such that the above example could be made to "work," expression would need to be of infinite size, which is clearly impossible.
To overcome these difficulties, variant includes special support for the boost::recursive_wrapper class template, which breaks the circular dependency at the heart of these problems. Further, boost::make_recursive_variant provides a more convenient syntax for declaring recursive variant types. Tutorials for use of these facilities is described in the section called “Recursive types with recursive_wrapper” and the section called “Recursive types with make_recursive_variant”.
Recursive types with recursive_wrapper
The following example demonstrates how recursive_wrapper could be used to solve the problem presented in the section called “Recursive variant types”:

typedef boost::variant< int , boost::recursive_wrapper< binary_op<add> > , boost::recursive_wrapper< binary_op<sub> > > expression;
Because variant provides special support for recursive_wrapper, clients may treat the resultant variant as though the wrapper were not present. This is seen in the implementation of the following visitor, which calculates the value of an expression without any reference to recursive_wrapper:

class calculator : public boost::static_visitor<int> { public:

int operator()(int value) const { return value; }

int operator()(const binary_op<add> & binary) const { return boost::apply_visitor( calculator(), binary.left ) + boost::apply_visitor( calculator(), binary.right ); }

int operator()(const binary_op<sub> & binary) const { return boost::apply_visitor( calculator(), binary.left ) - boost::apply_visitor( calculator(), binary.right ); }

};
Finally, we can demonstrate expression in action:

void f() { // result = ((7-3)+8) = 12 expression result( binary_op<add>( binary_op<sub>(7,3) , 8 ) );

assert( boost::apply_visitor(calculator(),result) == 12 ); }
Recursive types with make_recursive_variant
For some applications of recursive variant types, a user may be able to sacrifice the full flexibility of using recursive_wrapper with variant for the following convenient syntax:

typedef boost::make_recursive_variant< int , std::vector< boost::recursive_variant_ > >::type int_tree_t;
Use of the resultant variant type is as expected:

std::vector< int_tree_t > subresult; subresult.push_back(3); subresult.push_back(5);

std::vector< int_tree_t > result; result.push_back(1); result.push_back(subresult); result.push_back(7);

int_tree_t var(result);
To be clear, one might represent the resultant content of var as ( 1 ( 3 5 ) 7 ).
Finally, note that a type sequence can be used to specify the bounded types of a recursive variant via the use of boost::make_recursive_variant_over, whose semantics are the same as make_variant_over (which is described in the section called “Using a type sequence to specify bounded types”).
Portability
: Unfortunately, due to standard conformance issues in several compilers, make_recursive_variant is not universally supported. On these compilers the library indicates its lack of support via the definition of the preprocessor symbol BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT. Thus, unless working with highly-conformant compilers, maximum portability will be achieved by instead using recursive_wrapper, as described in the section called “Recursive types with recursive_wrapper”.
Binary visitation
As the tutorial above demonstrates, visitation is a powerful mechanism for manipulating variant content. Binary visitation further extends the power and flexibility of visitation by allowing simultaneous visitation of the content of two different variant objects.
Notably this feature requires that binary visitors are incompatible with the visitor objects discussed in the tutorial above, as they must operate on two arguments. The following demonstrates the implementation of a binary visitor:

class are_strict_equals : public boost::static_visitor<bool> { public:

template <typename T, typename U> bool operator()( const T &, const U & ) { return false; // cannot compare different types }

template <typename T> bool operator()( const T & lhs, const T & rhs ) { return lhs == rhs; }

};
As expected, the visitor is applied to two variant arguments by means of apply_visitor:

boost::variant
< int, std::string > v1( "hello" );

boost::variant
< double, std::string > v2( "hello" ); assert( boost::apply_visitor(are_strict_equals(), v1, v2) );

boost::variant
< int, const char * > v3( "hello" ); assert( !boost::apply_visitor(are_strict_equals(), v1, v3) );
Finally, we must note that the function object returned from the "delayed" form of apply_visitor also supports binary visitation, as the following demonstrates:

typedef boost::variant<double, std::string> my_variant;

std::vector< my_variant > seq1; seq1.push_back("pi is close to "); seq1.push_back(3.14);

std::list< my_variant > seq2; seq2.push_back("pi is close to "); seq2.push_back(3.14);

are_strict_equals visitor; assert( std::equal( v1.begin(), v1.end(), v2.begin() , boost::apply_visitor( visitor ) ) );
Reference
Reference
Concepts
BoundedType
The requirements on a bounded type are as follows:
•
CopyConstructible
[20.1.3].
•
Destructor upholds the no-throw exception-safety guarantee.
•
Complete at the point of variant template instantiation. (See boost::recursive_wrapper<T> for a type wrapper that accepts incomplete types to enable recursive variant types.)
Every type specified as a template argument to variant must at minimum fulfill the above requirements. In addition, certain features of variant are available only if its bounded types meet the requirements of these following additional concepts:
•
Assignable
: variant is itself Assignable if and only if every one of its bounded types meets the requirements of the concept. (Note that top-level const-qualified types and reference types do not meet these requirements.)
•
DefaultConstructible
[20.1.4]: variant is itself DefaultConstructible if and only if its first bounded type (i.e., T1) meets the requirements of the concept.
•
EqualityComparable
: variant is itself EqualityComparable if and only if every one of its bounded types meets the requirements of the concept.
•
LessThanComparable
: variant is itself LessThanComparable if and only if every one of its bounded types meets the requirements of the concept.
•
OutputStreamable
: variant is itself OutputStreamable if and only if every one of its bounded types meets the requirements of the concept.
StaticVisitor
The requirements on a static visitor of a type T are as follows:
•
Must allow invocation as a function by overloading operator(), unambiguously accepting any value of type T.
•
Must expose inner type result_type. (See boost::visitor_ptr for a solution to using functions as visitors.)
•
If result_type is not void, then each operation of the function object must return a value implicitly convertible to result_type.
Examples
The following class satisfies the requirements of a static visitor of several types (i.e., explicitly: int and std::string; or, e.g., implicitly: short and const char *; etc.):
class my_visitor : public boost::static_visitor<int> { public:

int operator()(int i) { return i * 2; }

int operator()(const std::string& s) { return s.length(); }

};
Another example is the following class, whose function-call operator is a member template, allowing it to operate on values of many types. Thus, the following class is a visitor of any type that supports streaming output (e.g., int, double, std::string, etc.):
class printer : public boost::static_visitor<> { template <typename T> void operator()(const T& t) { std::cout << t << std::endl; } };
OutputStreamable
The requirements on an output streamable type T are as follows:
•
For any object t of type T, std::cout << t must be a valid expression.
Header <boost/variant.hpp>
This header exists simply as a convenience to the user, including all of the headers in the boost/variant directory.
Header <boost/variant/variant_fwd.hpp>
Provides forward declarations of the boost::variant, boost::make_variant_over, boost::make_recursive_variant, and boost::make_recursive_variant_over class templates and the boost::recursive_variant_ tag type. Also defines several preprocessor symbols, as described below.
BOOST_VARIANT_LIMIT_TYPES
BOOST_VARIANT_ENUM_PARAMS
(param) BOOST_VARIANT_ENUM_SHIFTED_PARAMS(param) BOOST_VARIANT_NO_REFERENCE_SUPPORT BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
Macro BOOST_VARIANT_LIMIT_TYPES
Macro BOOST_VARIANT_LIMIT_TYPES -- Expands to the length of the template parameter list for variant.
BOOST_VARIANT_LIMIT_TYPES
BOOST_VARIANT_LIMIT_TYPES
Description
Description
Note
: Conforming implementations of variant must allow at least ten template arguments. That is, BOOST_VARIANT_LIMIT_TYPES must be greater or equal to 10.
Macro BOOST_VARIANT_ENUM_PARAMS
Macro BOOST_VARIANT_ENUM_PARAMS -- Enumerate parameters for use with variant.
BOOST_VARIANT_ENUM_PARAMS
BOOST_VARIANT_ENUM_PARAMS(param)
Description
Description
Expands to a comma-separated sequence of length BOOST_VARIANT_LIMIT_TYPES, where each element in the sequence consists of the concatenation of param with its zero-based index into the sequence. That is, param ## 0, param ## 1, ..., param ## BOOST_VARIANT_LIMIT_TYPES - 1.
Rationale
: This macro greatly simplifies for the user the process of declaring variant types in function templates or explicit partial specializations of class templates, as shown in the tutorial.
Macro BOOST_VARIANT_ENUM_SHIFTED_PARAMS
Macro BOOST_VARIANT_ENUM_SHIFTED_PARAMS -- Enumerate all but the first parameter for use with variant.
BOOST_VARIANT_ENUM_SHIFTED_PARAMS
BOOST_VARIANT_ENUM_SHIFTED_PARAMS(param)
Description
Description
Expands to a comma-separated sequence of length BOOST_VARIANT_LIMIT_TYPES - 1, where each element in the sequence consists of the concatenation of param with its one-based index into the sequence. That is, param ## 1, ..., param ## BOOST_VARIANT_LIMIT_TYPES - 1.
Note
: This macro results in the same expansion as BOOST_VARIANT_ENUM_PARAMS -- but without the first term.
Macro BOOST_VARIANT_NO_REFERENCE_SUPPORT
Macro BOOST_VARIANT_NO_REFERENCE_SUPPORT -- Indicates variant does not support references as bounded types.
BOOST_VARIANT_NO_REFERENCE_SUPPORT
BOOST_VARIANT_NO_REFERENCE_SUPPORT
Description
Description
Defined only if variant does not support references as bounded types.
Macro BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
Macro BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT -- Indicates absence of support for specifying the bounded types of a variant by the elements of a type sequence.
BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
Description
Description
Defined only if make_variant_over and make_recursive_variant_over are not supported for some reason on the target compiler.
Macro BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
Macro BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT -- Indicates make_recursive_variant operates in an implementation-defined manner.
BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
Description
Description
Defined only if make_recursive_variant does not operate as documented on the target compiler, but rather in an implementation-defined manner.
Implementation Note
: If BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT is defined for the target compiler, the current implementation uses the MPL lambda mechanism to approximate the desired behavior. (In most cases, however, such compilers do not have full lambda support either.)
Header <boost/variant/variant.hpp>
namespace
boost { template<typename T1, typename T2 = unspecified, ..., typename TN = unspecified> class variant;

template
<typename Sequence> class make_variant_over; template<typename T1, typename T2, ..., typename TN> void swap(variant<T1, T2, ..., TN> &, variant<T1, T2, ..., TN> &); template<typename ElemType, typename Traits, typename T1, typename T2, ..., typename TN> std::basic_ostream<ElemType,Traits> & operator<<(std::basic_ostream<ElemType,Traits> &, const variant<T1, T2, ..., TN> &); }
Class template variant
Class template variant -- Safe, generic, stack-based discriminated union container.
boost::variant
template
<typename T1, typename T2 = unspecified, ..., typename TN = unspecified> class variant { public: // types typedef unspecified types;

// construct/copy/destruct
variant
(); variant(const variant &); template<typename T> variant(T &); template<typename T> variant(const T &); template<typename U1, typename U2, ..., typename UN> variant(variant<U1, U2, ..., UN> &); template<typename U1, typename U2, ..., typename UN> variant(const variant<U1, U2, ..., UN> &); ~variant();

// modifiers
void
swap
(variant &); variant & operator=(const variant &); template<typename T> variant & operator=(const T &);

// queries
int
which
() const; bool empty() const; const std::type_info & type() const;

// relational
bool
operator
==
(const variant &) const; template<typename U> void operator==(const U &) const; bool operator<(const variant &) const; template<typename U> void operator<(const U &) const; };
Description
Description
The variant class template (inspired by Andrei Alexandrescu's class of the same name [Ale01A]) is an efficient, recursive-capable, bounded discriminated union value type capable of containing any value type (either POD or non-POD). It supports construction from any type convertible to one of its bounded types or from a source variant whose bounded types are each convertible to one of the destination variant's bounded types. As well, through apply_visitor, variant supports compile-time checked, type-safe visitation; and through get, variant supports run-time checked, type-safe value retrieval.
Notes
:
•
The bounded types of the variant are exposed via the nested typedef types, which is an MPL-compatible Sequence containing the set of types that must be handled by any visitor to the variant.
•
All members of variant satisfy at least the basic guarantee of exception-safety. That is, all operations on a variant remain defined even after previous operations have failed.
•
Each type specified as a template argument to variant must meet the requirements of the BoundedType concept.
•
Each type specified as a template argument to variant must be distinct after removal of qualifiers. Thus, for instance, both variant<int, int> and variant<int, const int> have undefined behavior.
•
Conforming implementations of variant must allow at least ten types as template arguments. The exact number of allowed arguments is exposed by the preprocessor macro BOOST_VARIANT_LIMIT_TYPES. (See make_variant_over for a means to specify the bounded types of a variant by the elements of an MPL or compatible Sequence, thus overcoming this limitation.)
variant construct/copy/destruct
variant
construct/copy/destruct
1.
variant();
Requires
The first bounded type of the variant (i.e., T1) must fulfill the requirements of the DefaultConstructible [20.1.4] concept.
Postconditions
Content of *this is the default value of the first bounded type (i.e, T1).
Throws
May fail with any exceptions arising from the default constructor of T1.
2.
variant(const variant & other);
Postconditions
Content of *this is a copy of the content of other.
Throws
May fail with any exceptions arising from the copy constructor of other's contained type.
3.
template
<typename T> variant(T & operand);
Requires
T
must be unambiguously convertible to one of the bounded types (i.e., T1, T2, etc.).
Postconditions
Content of *this is the best conversion of operand to one of the bounded types, as determined by standard overload resolution rules.
Throws
May fail with any exceptions arising from the conversion of operand to one of the bounded types.
4.
template
<typename T> variant(const T & operand);
Notes
Same semantics as previous constructor, but allows construction from temporaries.
5.
template
<typename U1, typename U2, ..., typename UN> variant(variant<U1, U2, ..., UN> & operand);
Requires
Every
one of U1, U2, ..., UN must have an unambiguous conversion to one of the bounded types (i.e., T1, T2, ..., TN).
Postconditions
If variant<U1, U2, ..., UN> is itself one of the bounded types, then content of *this is a copy of operand. Otherwise, content of *this is the best conversion of the content of operand to one of the bounded types, as determined by standard overload resolution rules.
Throws
If variant<U1, U2, ..., UN> is itself one of the bounded types, then may fail with any exceptions arising from the copy constructor of variant<U1, U2, ..., UN>. Otherwise, may fail with any exceptions arising from the conversion of the content of operand to one of the bounded types.
6.
template
<typename U1, typename U2, ..., typename UN> variant(const variant<U1, U2, ..., UN> & operand);
Notes
Same semantics as previous constructor, but allows construction from temporaries.
7.
~variant();
Effects
Destroys the content of *this.
Throws
Will not throw.
variant modifiers
variant
modifiers
1.
void
swap(variant & other);
Requires
Every bounded type must fulfill the requirements of the Assignable concept.
Effects
Interchanges the content of *this and other.
Throws
If the contained type of other is the same as the contained type of *this, then may fail with any exceptions arising from the swap of the contents of *this and other. Otherwise, may fail with any exceptions arising from either of the copy constructors of the contained types. Also, in the event of insufficient memory, may fail with std::bad_alloc (why?).
2.
variant & operator=(const variant & rhs);
Requires
Every bounded type must fulfill the requirements of the Assignable concept.
Effects
If the contained type of rhs is the same as the contained type of *this, then assigns the content of rhs into the content of *this. Otherwise, makes the content of *this a copy of the content of rhs, destroying the previous content of *this.
Throws
If the contained type of rhs is the same as the contained type of *this, then may fail with any exceptions arising from the assignment of the content of rhs into the content *this. Otherwise, may fail with any exceptions arising from the copy constructor of the contained type of rhs. Also, in the event of insufficient memory, may fail with std::bad_alloc (why?).
3.
template
<typename T> variant & operator=(const T & rhs);
Requires
•
T
must be unambiguously convertible to one of the bounded types (i.e., T1, T2, etc.).
•
Every bounded type must fulfill the requirements of the Assignable concept.
Effects
If the contained type of *this is T, then assigns rhs into the content of *this. Otherwise, makes the content of *this the best conversion of rhs to one of the bounded types, as determined by standard overload resolution rules, destroying the previous content of *this.
Throws
If the contained type of *this is T, then may fail with any exceptions arising from the assignment of rhs into the content *this. Otherwise, may fail with any exceptions arising from the conversion of rhs to one of the bounded types. Also, in the event of insufficient memory, may fail with std::bad_alloc (why?).
variant queries
variant
queries
1.
int
which() const;
Returns
The zero-based index into the set of bounded types of the contained type of *this. (For instance, if called on a variant<int, std::string> object containing a std::string, which() would return 1.)
Throws
Will not throw.
2.
bool
empty() const;
Returns
false
: variant always contains exactly one of its bounded types. (See the section called “"Never-Empty" Guarantee” for more information.)
Rationale
Facilitates generic compatibility with boost::any.
Throws
Will not throw.
3.
const
std::type_info & type() const;
Returns
typeid(x)
, where x is the the content of *this.
Throws
Will not throw.
variant relational
variant
relational
1.
bool
operator
==(const variant & rhs) const; template<typename U> void operator==(const U & ) const;
Notes
The overload returning void exists only to prohibit implicit conversion of the operator's right-hand side to variant; thus, its use will (purposefully) result in a compile-time error.
Requires
Every bounded type of the variant must fulfill the requirements of the EqualityComparable concept.
Returns
true
iff which() == rhs.which()and content_this == content_rhs, where content_this is the content of *this and content_rhs is the content of rhs.
Throws
If which() == rhs.which() then may fail with any exceptions arising from operator==(T,T), where T is the contained type of *this.
2.
bool
operator
<(const variant & rhs) const; template<typename U> void operator<(const U & ) const;
Notes
The overload returning void exists only to prohibit implicit conversion of the operator's right-hand side to variant; thus, its use will (purposefully) result in a compile-time error.
Requires
Every bounded type of the variant must fulfill the requirements of the LessThanComparable concept.
Returns
If which() == rhs.which() then: content_this < content_rhs, where content_this is the content of *this and content_rhs is the content of rhs. Otherwise: which() < rhs.which().
Throws
If which() == rhs.which() then may fail with any exceptions arising from operator<(T,T), where T is the contained type of *this.
Function template swap
Function template swap --
boost::swap
template
<typename T1, typename T2, ..., typename TN> void swap(variant<T1, T2, ..., TN> & lhs, variant<T1, T2, ..., TN> & rhs);
Description
Description
Effects
Swaps lhs with rhs by application of variant::swap.
Throws
May fail with any exception arising from variant::swap.
Function template operator<<
Function template operator<< -- Provides streaming output for variant types.
boost::operator<<
template
<typename ElemType, typename Traits, typename T1, typename T2, ..., typename TN> std::basic_ostream<ElemType,Traits> & operator<<(std::basic_ostream<ElemType,Traits> & out, const variant<T1, T2, ..., TN> & rhs);
Description
Description
Requires
Every bounded type of the variant must fulfill the requirements of the OutputStreamable concept.
Effects
Calls out << x, where x is the content of rhs.
Class template make_variant_over
Class template make_variant_over -- Exposes a variant whose bounded types are the elements of the given type sequence.
boost::make_variant_over
template
<typename Sequence> class make_variant_over { public: // types typedef variant< unspecified > type; };
Description
Description
type
has behavior equivalent in every respect to variant< Sequence[0], Sequence[1], ... > (where Sequence[i] denotes the i-th element of Sequence), except that no upper limit is imposed on the number of types.
Notes
:
•
Sequence
must meet the requirements of MPL's Sequence concept.
•
Due to standard conformance problems in several compilers, make_variant_over may not be supported on your compiler. See BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT for more information.
Header <boost/variant/recursive_variant.hpp>
namespace
boost { typedef unspecified recursive_variant_;

template
<typename T1, typename T2 = unspecified, ..., typename TN = unspecified> class make_recursive_variant; template<typename Sequence> class make_recursive_variant_over; }
Class template make_recursive_variant
Class template make_recursive_variant -- Simplifies declaration of recursive variant types.
boost::make_recursive_variant
template
<typename T1, typename T2 = unspecified, ..., typename TN = unspecified> class make_recursive_variant { public: // types typedef boost::variant< unspecified > type; };
Description
Description
type
has behavior equivalent in every respect to some variant< U1, U2, ..., UN >, where each type Ui is the result of the corresponding type Ti undergone a transformation function. The following pseudo-code specifies the behavior of this transformation (call it substitute):

•
If Ti is boost::recursive_variant_ then: variant< U1, U2, ..., UN >;
•
Else if Ti is of the form X * then: substitute(X) *;
•
Else if Ti is of the form X & then: substitute(X) &;
•
Else if Ti is of the form R (*)( X1, X2, ..., XN ) then: substitute(R) (*)( substitute(X1), substitute(X2), ..., substitute(XN) );
•
Else if Ti is of the form F < X1, X2, ..., XN > then: F< substitute(X1), substitute(X2), ..., substitute(XN) >;
•
Else: Ti.
Note that cv-qualifiers are preserved and that the actual process is generally a bit more complicated. However, the above does convey the essential idea as well as describe the extent of the substititions.
Use of make_recursive_variant is demonstrated in the section called “Recursive types with make_recursive_variant”.
Portability
: Due to standard conformance issues in several compilers, make_recursive_variant is not universally supported. On these compilers the library indicates its lack of support via the definition of the preprocessor symbol BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT.
Class template make_recursive_variant_over
Class template make_recursive_variant_over -- Exposes a recursive variant whose bounded types are the elements of the given type sequence.
boost::make_recursive_variant_over
template
<typename Sequence> class make_recursive_variant_over { public: // types typedef variant< unspecified > type; };
Description
Description
type
has behavior equivalent in every respect to make_recursive_variant< Sequence[0], Sequence[1], ... >::type (where Sequence[i] denotes the i-th element of Sequence), except that no upper limit is imposed on the number of types.
Notes
:
•
Sequence
must meet the requirements of MPL's Sequence concept.
•
Due to standard conformance problems in several compilers, make_recursive_variant_over may not be supported on your compiler. See BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT for more information.
Header <boost/variant/recursive_wrapper.hpp>
namespace
boost { template<typename T> class recursive_wrapper; template<typename T> class is_recursive_wrapper; template<typename T> class unwrap_recursive_wrapper; }
Class template recursive_wrapper
Class template recursive_wrapper -- Solves circular dependencies, enabling recursive types.
boost::recursive_wrapper
template
<typename T> class recursive_wrapper { public: // types typedef T type;

// construct/copy/destruct
recursive_wrapper
(); recursive_wrapper(const recursive_wrapper &); recursive_wrapper(const T &); ~recursive_wrapper();

// modifiers
void
swap
(recursive_wrapper &); recursive_wrapper & operator=(const recursive_wrapper &); recursive_wrapper & operator=(const T &);

// queries
T & get(); const T & get() const; T * get_pointer(); const T * get_pointer() const; };
Description
Description
The recursive_wrapper class template has an interface similar to a simple value container, but its content is allocated dynamically. This allows recursive_wrapper to hold types T whose member data leads to a circular dependency (e.g., a data member of T has a data member of type T).
The application of recursive_wrapper is easiest understood in context. See the section called “Recursive types with recursive_wrapper” for a demonstration of a common use of the class template.
Notes
:
•
Any type specified as the template argument to recursive_wrapper must be capable of construction via operator new. Thus, for instance, references are not supported.
recursive_wrapper construct/copy/destruct
recursive_wrapper
construct/copy/destruct
1.
recursive_wrapper();
Initializes *this by default construction of T.
Requires
T
must fulfill the requirements of the DefaultConstructible [20.1.4] concept.
Throws
May fail with any exceptions arising from the default constructor of T or, in the event of insufficient memory, with std::bad_alloc.
2.
recursive_wrapper(const recursive_wrapper & other);
Copies the content of other into *this.
Throws
May fail with any exceptions arising from the copy constructor of T or, in the event of insufficient memory, with std::bad_alloc.
3.
recursive_wrapper(const T & operand);
Copies operand into *this.
Throws
May fail with any exceptions arising from the copy constructor of T or, in the event of insufficient memory, with std::bad_alloc.
4.
~recursive_wrapper();
Deletes the content of *this.
Throws
Will not throw.
recursive_wrapper modifiers
recursive_wrapper
modifiers
1.
void
swap(recursive_wrapper & other);
Exchanges contents of *this and other.
Throws
Will not throw.
2.
recursive_wrapper & operator=(const recursive_wrapper & rhs);
Assigns the content of rhs to the content of *this.
Requires
T
must fulfill the requirements of the Assignable concept.
Throws
May fail with any exceptions arising from the assignment operator of T.
3.
recursive_wrapper & operator=(const T & rhs);
Assigns rhs into the content of *this.
Requires
T
must fulfill the requirements of the Assignable concept.
Throws
May fail with any exceptions arising from the assignment operator of T.
recursive_wrapper queries
recursive_wrapper
queries
1.
T & get(); const T & get() const;
Returns a reference to the content of *this.
Throws
Will not throw.
2.
T * get_pointer(); const T * get_pointer() const;
Returns a pointer to the content of *this.
Throws
Will not throw.
Class template is_recursive_wrapper
Class template is_recursive_wrapper -- Determines whether the specified type is a specialization of recursive_wrapper.
boost::is_recursive_wrapper
template
<typename T> class is_recursive_wrapper { public: // types typedef unspecified type;

// static constants
static
const
bool
value = unspecified; };
Description
Description
Value is true iff T is a specialization of recursive_wrapper.
Note
: is_recursive_wrapper is a model of MPL's IntegralConstant concept.
Class template unwrap_recursive_wrapper
Class template unwrap_recursive_wrapper -- Unwraps the specified argument if given a specialization of recursive_wrapper.
boost::unwrap_recursive_wrapper
template
<typename T> class unwrap_recursive_wrapper { public: // types typedef unspecified type; };
Description
Description
type
is equivalent to T::type if T is a specialization of recursive_wrapper. Otherwise, type is equivalent to T.
Header <boost/variant/apply_visitor.hpp>
namespace
boost { template<typename Visitor> class apply_visitor_delayed_t; template<typename Visitor, typename Variant> typename Visitor::result_type apply_visitor(Visitor &, Variant &); template<typename Visitor, typename Variant> typename Visitor::result_type apply_visitor(const Visitor &, Variant &); template<typename BinaryVisitor, typename Variant1, typename Variant2> typename BinaryVisitor::result_type apply_visitor(BinaryVisitor &, Variant1 &, Variant2 &); template<typename BinaryVisitor, typename Variant1, typename Variant2> typename BinaryVisitor::result_type apply_visitor(const BinaryVisitor &, Variant1 &, Variant2 &); template<typename Visitor> apply_visitor_delayed_t<Visitor> apply_visitor(Visitor &); }
Class template apply_visitor_delayed_t
Class template apply_visitor_delayed_t -- Adapts a visitor for use as a function object.
boost::apply_visitor_delayed_t
template
<typename Visitor> class apply_visitor_delayed_t { public: // types typedef typename Visitor::result_type result_type;

// construct/copy/destruct
explicit
apply_visitor_delayed_t
(Visitor &);

// function object interface
template
<typename Variant> result_type operator()(Variant &); template<typename Variant1, typename Variant2> result_type operator()(Variant1 &, Variant2 &); };
Description
Description
Adapts the function given at construction for use as a function object. This is useful, for example, when one needs to operate on each element of a sequence of variant objects using a standard library algorithm such as std::for_each.
See the "visitor-only" form of apply_visitor for a simple way to create apply_visitor_delayed_t objects.
apply_visitor_delayed_t construct/copy/destruct
apply_visitor_delayed_t
construct/copy/destruct
1.
explicit
apply_visitor_delayed_t(Visitor & visitor);
Effects
Constructs the function object with the given visitor.
apply_visitor_delayed_t function object interface
apply_visitor_delayed_t
function object interface
1.
template
<typename Variant> result_type operator()(Variant & operand); template<typename Variant1, typename Variant2> result_type operator()(Variant1 & operand1, Variant2 & operand2);
Invokes apply_visitor on the stored visitor using the given operands.
Function apply_visitor
Function apply_visitor -- Allows compile-time checked type-safe application of the given visitor to the content of the given variant, ensuring that all types are handled by the visitor.
boost::apply_visitor
template
<typename Visitor, typename Variant> typename Visitor::result_type apply_visitor(Visitor & visitor, Variant & operand); template<typename Visitor, typename Variant> typename Visitor::result_type apply_visitor(const Visitor & visitor, Variant & operand); template<typename BinaryVisitor, typename Variant1, typename Variant2> typename BinaryVisitor::result_type apply_visitor(BinaryVisitor & visitor, Variant1 & operand1, Variant2 & operand2); template<typename BinaryVisitor, typename Variant1, typename Variant2> typename BinaryVisitor::result_type apply_visitor(const BinaryVisitor & visitor, Variant1 & operand1, Variant2 & operand2); template<typename Visitor> apply_visitor_delayed_t<Visitor> apply_visitor(Visitor & visitor);
Description
Description
The behavior of apply_visitor is dependent on the number of arguments on which it operates (i.e., other than the visitor). The function behaves as follows:

•
Overloads accepting one operand invoke the unary function call operator of the given visitor on the content of the given variant operand.
•
Overloads accepting two operands invoke the binary function call operator of the given visitor on the content of the given variant operands.
•
The overload accepting only a visitor returns a generic function object that accepts either one or two arguments and invokes apply_visitor using these arguments and visitor, thus behaving as specified above. (This behavior is particularly useful, for example, when one needs to operate on each element of a sequence of variant objects using a standard library algorithm.)
Returns
The overloads acccepting operands return the result of applying the given visitor to the content of the given operands. The overload accepting only a visitor return a function object, thus delaying application of the visitor to any operands.
Requires
The given visitor must fulfill the StaticVisitor concept requirements with respect to each of the bounded types of the given variant.
Throws
The overloads accepting operands throw only if the given visitor throws when applied. The overload accepting only a visitor will not throw. (Note, however, that the returned function object may throw when invoked.)
Header <boost/variant/get.hpp>
namespace
boost { class bad_get; template<typename U, typename T1, typename T2, ..., typename TN> U * get(variant<T1, T2, ..., TN> *); template<typename U, typename T1, typename T2, ..., typename TN> const U * get(const variant<T1, T2, ..., TN> *); template<typename U, typename T1, typename T2, ..., typename TN> U & get(variant<T1, T2, ..., TN> &); template<typename U, typename T1, typename T2, ..., typename TN> const U & get(const variant<T1, T2, ..., TN> &); }
Class bad_get
Class bad_get -- The exception thrown in the event of a failed application of boost::get on the given operand value.
boost::bad_get
class
bad_get : public std::exception { public: virtual const char * what() const; };
Description
Description
virtual
const
char
* what() const;
Function get
Function get -- Retrieves a value of a specified type from a given variant.
boost::get
template
<typename U, typename T1, typename T2, ..., typename TN> U * get(variant<T1, T2, ..., TN> * operand); template<typename U, typename T1, typename T2, ..., typename TN> const U * get(const variant<T1, T2, ..., TN> * operand); template<typename U, typename T1, typename T2, ..., typename TN> U & get(variant<T1, T2, ..., TN> & operand); template<typename U, typename T1, typename T2, ..., typename TN> const U & get(const variant<T1, T2, ..., TN> & operand);
Description
Description
The get function allows run-time checked, type-safe retrieval of the content of the given variant. The function succeeds only if the content is of the specified type U, with failure indicated as described below.
Warning
: After either operand or its content is destroyed (e.g., when the given variant is assigned a value of different type), the returned reference is invalidated. Thus, significant care and caution must be extended when handling the returned reference.
Notes
As part of its guarantee of type-safety, get enforces const-correctness. Thus, the specified type U must be const-qualified whenever operand or its content is likewise const-qualified. The converse, however, is not required: that is, the specified type U may be const-qualified even when operand and its content are not.
Returns
If passed a pointer, get returns a pointer to the value content if it is of the specified type U; otherwise, a null pointer is returned. If passed a reference, get returns a reference to the value content if it is of the specified type U; otherwise, an exception is thrown (see below).
Throws
Overloads taking a variant pointer will not throw; the overloads taking a variant reference throw bad_get if the content is not of the specified type U.
Rationale
While visitation via apply_visitor is generally prefered due to its greater safety, get may may be more convenient in some cases due to its straightforward usage.
Header <boost/variant/bad_visit.hpp>
namespace
boost { class bad_visit; }
Class bad_visit
Class bad_visit -- The exception thrown in the event of a visitor unable to handle the visited value.
boost::bad_visit
class
bad_visit : public std::exception { public: virtual const char * what() const; };
Description
Description
virtual
const
char
* what() const;
Header <boost/variant/static_visitor.hpp>
namespace
boost { template<typename ResultType> class static_visitor; }
Class template static_visitor
Class template static_visitor -- Convenient base type for static visitors.
boost::static_visitor
template
<typename ResultType> class static_visitor { public: // types typedef ResultType result_type; // Exposes result_type member as required by StaticVisitor concept. };
Description
Description
Denotes the intent of the deriving class as meeting the requirements of a static visitor of some type. Also exposes the inner type result_type as required by the StaticVisitor concept.
Notes
: static_visitor is intended for use as a base type only and is therefore noninstantiable.
Header <boost/variant/visitor_ptr.hpp>
namespace
boost { template<typename T, typename R> class visitor_ptr_t; template<typename R, typename T> visitor_ptr_t<T,R> visitor_ptr(R (*)(T)); }
Class template visitor_ptr_t
Class template visitor_ptr_t -- Adapts a function pointer for use as a static visitor.
boost::visitor_ptr_t
template
<typename T, typename R> class visitor_ptr_t : public static_visitor<R> { public: // construct/copy/destruct explicit visitor_ptr_t(R (*)(T));

// static visitor interfaces
R operator()(unspecified-forwarding-type); template<typename U> void operator()(const U&); };
Description
Description
Adapts the function given at construction for use as a static visitor of type T with result type R.
visitor_ptr_t construct/copy/destruct
visitor_ptr_t
construct/copy/destruct
1.
explicit
visitor_ptr_t(R (*)(T) );
Effects
Constructs the visitor with the given function.
visitor_ptr_t static visitor interfaces
visitor_ptr_t
static visitor interfaces
1.
R operator()(unspecified-forwarding-type operand); template<typename U> void operator()(const U& );
Effects
If passed a value or reference of type T, it invokes the function given at construction, appropriately forwarding operand.
Returns
Returns the result of the function invocation.
Throws
The overload taking a value or reference of type T throws if the invoked function throws. The overload taking all other values always throws bad_visit.
Function template visitor_ptr
Function template visitor_ptr -- Returns a visitor object that adapts function pointers for use as a static visitor.
boost::visitor_ptr
template
<typename R, typename T> visitor_ptr_t<T,R> visitor_ptr(R (*)(T) );
Description
Description
Constructs and returns a visitor_ptr_t adaptor over the given function.
Returns
Returns a visitor_ptr_t visitor object that, when applied, invokes the given function.
Throws
Will not throw. (Note, however, that the returned visitor object may throw when applied.)
Design Overview
Design Overview
"Never-Empty" Guarantee
The Guarantee
All instances v of type variant<T1,T2,...,TN> guarantee that v has constructed content of one of the types Ti, even if an operation on v has previously failed.
This implies that variant may be viewed precisely as a union of exactly its bounded types. This "never-empty" property insulates the user from the possibility of undefined variant content and the significant additional complexity-of-use attendant with such a possibility.
The Implementation Problem
While the never-empty guarantee might at first seem "obvious," it is in fact not even straightforward how to implement it in general (i.e., without unreasonably restrictive additional requirements on bounded types).
The central difficulty emerges in the details of variant assignment. Given two instances v1 and v2 of some concrete variant type, there are two distinct, fundamental cases we must consider for the assignment v1 = v2.
First consider the case that v1 and v2 each contains a value of the same type. Call this type T. In this situation, assignment is perfectly straightforward: use T::operator=.
However, we must also consider the case that v1 and v2 contain values of distinct types. Call these types T and U. At this point, since variant manages its content on the stack, the left-hand side of the assignment (i.e., v1) must destroy its content so as to permit in-place copy-construction of the content of the right-hand side (i.e., v2). In the end, whereas v1 began with content of type T, it ends with content of type U, namely a copy of the content of v2.
The crux of the problem, then, is this: in the event that copy-construction of the content of v2 fails, how can v1 maintain its "never-empty" guarantee? By the time copy-construction from v2 is attempted, v1 has already destroyed its content!
The "Ideal" Solution: False Hopes
Upon learning of this dilemma, clever individuals may propose the following scheme hoping to solve the problem:

1.
Provide some "backup" storage, appropriately aligned, capable of holding values of the contained type of the left-hand side.
2.
Copy the memory (e.g., using memcpy) of the storage of the left-hand side to the backup storage.
3.
Attempt a copy of the right-hand side content to the (now-replicated) left-hand side storage.
4.
In the event of an exception from the copy, restore the backup (i.e., copy the memory from the backup storage back into the left-hand side storage).
5.
Otherwise, in the event of success, now copy the memory of the left-hand side storage to another "temporary" aligned storage.
6.
Now restore the backup (i.e., again copying the memory) to the left-hand side storage; with the "old" content now restored, invoke the destructor of the contained type on the storage of the left-hand side.
7.
Finally, copy the memory of the temporary storage to the (now-empty) storage of the left-hand side.
While complicated, it appears such a scheme could provide the desired safety in a relatively efficient manner. In fact, several early iterations of the library implemented this very approach.
Unfortunately, as Dave Abraham's first noted, the scheme results in undefined behavior:

"That's a lot of code to read through, but if it's doing what I think it's doing, it's undefined behavior.
"Is the trick to move the bits for an existing object into a buffer so we can tentatively construct a new object in that memory, and later move the old bits back temporarily to destroy the old object?
"The standard does not give license to do that: only one object may have a given address at a time. See 3.8, and particularly paragraph 4."
Additionally, as close examination quickly reveals, the scheme has the potential to create irreconcilable race-conditions in concurrent environments.
Ultimately, even if the above scheme could be made to work on certain platforms with particular compilers, it is still necessary to find a portable solution.
An Initial Solution: Double Storage
Upon learning of the infeasibility of the above scheme, Anthony Williams proposed in [Wil02] a scheme that served as the basis for a portable solution in some pre-release implementations of variant.
The essential idea to this scheme, which shall be referred to as the "double storage" scheme, is to provide enough space within a variant to hold two separate values of any of the bounded types.
With the secondary storage, a copy the right-hand side can be attempted without first destroying the content of the left-hand side; accordingly, the content of the left-hand side remains available in the event of an exception.
Thus, with this scheme, the variant implementation needs only to keep track of which storage contains the content -- and dispatch any visitation requests, queries, etc. accordingly.
The most obvious flaw to this approach is the space overhead incurred. Though some optimizations could be applied in special cases to eliminate the need for double storage -- for certain bounded types or in some cases entirely (see the section called “Enabling Optimizations” for more details) -- many users on the Boost mailing list strongly objected to the use of double storage. In particular, it was noted that the overhead of double storage would be at play at all times -- even if assignment to variant never occurred. For this reason and others, a new approach was developed.
Current Approach: Temporary Heap Backup
Despite the many objections to the double storage solution, it was realized that no replacement would be without drawbacks. Thus, a compromise was desired.
To this end, Dave Abrahams suggested to include the following in the behavior specification for variant assignment: "variant assignment from one type to another may incur dynamic allocation." That is, while variant would continue to store its content in situ after construction and after assignment involving identical contained types, variant would store its content on the heap after assignment involving distinct contained types.
The algorithm for assignment would proceed as follows:

1.
Copy-construct the content of the right-hand side to the heap; call the pointer to this data p.
2.
Destroy the content of the left-hand side.
3.
Copy p to the left-hand side storage.

Since all operations on pointers are nothrow, this scheme would allow variant to meet its never-empty guarantee.
The most obvious concern with this approach is that while it certainly eliminates the space overhead of double storage, it introduces the overhead of dynamic-allocation to variant assignment -- not just in terms of the initial allocation but also as a result of the continued storage of the content on the heap. While the former problem is unavoidable, the latter problem may be avoided with the following "temporary heap backup" technique:

1.
Copy-construct the content of the left-hand side to the heap; call the pointer to this data backup.
2.
Destroy the content of the left-hand side.
3.
Copy-construct the content of the right-hand side in the (now-empty) storage of the left-hand side.
4.
In the event of failure, copy backup to the left-hand side storage.
5.
In the event of success, deallocate the data pointed to by backup.
With this technique: 1) only a single storage is used; 2) allocation is on the heap in the long-term only if the assignment fails; and 3) after any successful assignment, storage within the variant is guaranteed. For the purposes of the initial release of the library, these characteristics were deemed a satisfactory compromise solution.
There remain notable shortcomings, however. In particular, there may be some users for which heap allocation must be avoided at all costs; for other users, any allocation may need to occur via a user-supplied allocator. These issues will be addressed in the future (see the section called “Future Direction: Policy-based Implementation”). For now, though, the library treats storage of its content as an implementation detail. Nonetheless, as described in the next section, there are certain things the user can do to ensure the greatest efficiency for variant instances (see the section called “Enabling Optimizations” for details).
Enabling Optimizations
As described in the section called “The Implementation Problem”, the central difficulty in implementing the never-empty guarantee is the possibility of failed copy-construction during variant assignment. Yet types with nothrow copy constructors clearly never face this possibility. Similarly, if one of the bounded types of the variant is nothrow default-constructible, then such a type could be used as a safe "fallback" type in the event of failed copy construction.
Accordingly, variant is designed to enable the following optimizations once the following criteria on its bounded types are met:

•
For each bounded type T that is nothrow copy-constructible (as indicated by boost::has_nothrow_copy), the library guarantees variant will use only single storage and in-place construction for T.
•
If any bounded type is nothrow default-constructible (as indicated by boost::has_nothrow_constructor), the library guarantees variant will use only single storage and in-place construction for every bounded type in the variant. Note, however, that in the event of assignment failure, an unspecified nothrow default-constructible bounded type will be default-constructed in the left-hand side operand so as to preserve the never-empty guarantee.
Caveat
: On most platforms, the Type Traits templates has_nothrow_copy and has_nothrow_constructor by default return false for all class and struct types. It is necessary therefore to provide specializations of these templates as appropriate for user-defined types, as demonstrated in the following:

// ...in your code (at file scope)...

namespace boost {

template <> struct has_nothrow_copy< myUDT > : mpl::true_ { };

}
Implementation Note
: So as to make the behavior of variant more predictable in the aftermath of an exception, the current implementation prefers to default-construct boost::blank if specified as a bounded type instead of other nothrow default-constructible bounded types. (If this is deemed to be a useful feature, it will become part of the specification for variant; otherwise, it may be obsoleted. Please provide feedback to the Boost mailing list.)
Future Direction: Policy-based Implementation
As the previous sections have demonstrated, much effort has been expended in an attempt to provide a balance between performance, data size, and heap usage. Further, significant optimizations may be enabled in variant on the basis of certain traits of its bounded types.
However, there will be some users for whom the chosen compromise is unsatisfactory (e.g.: heap allocation must be avoided at all costs; if heap allocation is used, custom allocators must be used; etc.). For this reason, a future version of the library will support a policy-based implementation of variant. While this will not eliminate the problems described in the previous sections, it will allow the decisions regarding tradeoffs to be decided by the user rather than the library designers.
Miscellaneous Notes
Miscellaneous Notes
Boost.Variant vs. Boost.Any
As a discriminated union container, the Variant library shares many of the same features of the Any library. However, since neither library wholly encapsulates the features of the other, one library cannot be generally recommended for use over the other.
That said, Boost.Variant has several advantages over Boost.Any, such as:

•
Boost.Variant guarantees the type of its content is one of a finite, user-specified set of types.
•
Boost.Variant provides compile-time checked visitation of its content. (By contrast, the current version of Boost.Any provides no visitation mechanism at all; but even if it did, it would need to be checked at run-time.)
•
Boost.Variant enables generic visitation of its content. (Even if Boost.Any did provide a visitation mechanism, it would enable visitation only of explicitly-specified types.)
•
Boost.Variant offers an efficient, stack-based storage scheme (avoiding the overhead of dynamic allocation).
Of course, Boost.Any has several advantages over Boost.Variant, such as:

•
Boost.Any, as its name implies, allows virtually any type for its content, providing great flexibility.
•
Boost.Any provides the no-throw guarantee of exception safety for its swap operation.
•
Boost.Any makes little use of template metaprogramming techniques (avoiding potentially hard-to-read error messages and significant compile-time processor and memory demands).
Portability
The library aims for 100% ANSI/ISO C++ conformance. However, this is strictly impossible due to the inherently non-portable nature of the Type Traits library's type_with_alignment facility. In practice though, no compilers or platforms have been discovered where this reliance on undefined behavior has been an issue.
Additionally, significant effort has been expended to ensure proper functioning despite various compiler bugs and other conformance problems. To date the library testsuite has been compiled and tested successfully on at least the following compilers for basic and advanced functionality:

Basic
variant<T&>
make_variant_over
make_recursive_variant
Borland C++ 5.5.1 and 5.6.4
X
X
Comeau C++ 4.3.0
X
X
X
X
GNU GCC 3.3.1
X
X
X
X
GNU GCC 2.95.3
X
X
X
Intel C++ 7.0
X
X
X
Metrowerks CodeWarrior 8.3
X
X
X
Microsoft Visual C++ 7.1
X
X
X
X
Microsoft Visual C++ 6 SP5 and 7
X

Finally, the current state of the testsuite in CVS may be found on the Test Summary page. Please note, however, that this page reports on day-to-day changes to inter-release code found in the Boost CVS and thus likely does not match the state of code found in Boost releases.
Troubleshooting
Due to the heavy use of templates in the implementation of variant, it is not uncommon when compiling to encounter problems related to template instantiaton depth, compiler memory, etc. This section attempts to provide advice to common problems experienced on several popular compilers.
(This section is still in progress, with additional advice/feedback welcome. Please post to the Boost-Users list with any useful experiences you may have.)
"Template instantiation depth exceeds maximum"
GNU GCC
The compiler option -ftemplate-depth-NN can increase the maximum allowed instantiation depth. (Try -ftemplate-depth-50.)
"Internal heap limit reached"
Microsoft Visual C++
The compiler option /ZmNNN can increase the memory allocation limit. The NNN is a scaling percentage (i.e., 100 denotes the default limit). (Try /Zm200.)
Acknowledgments
Eric Friedman and Itay Maman designed the initial submission; Eric was the primary implementer.
Eric is also the library maintainer and has expanded upon the initial submission -- adding make_recursive_variant, make_variant_over, support for reference content, etc.
Andrei Alexandrescu's work in [Ale01a] and [Ale02] inspired the library's design.
Jeff Garland was the formal review manager.
Douglas Gregor, Dave Abrahams, Anthony Williams, Fernando Cacciola, Joel de Guzman, Dirk Schreib, Brad King, Giovanni Bajo, Eugene Gladyshev, and others provided helpful feedback and suggestions to refine the semantics, interface, and implementation of the library.
References
References
[Abr00]
David Abrahams. "Exception-Safety in Generic Components." M. Jazayeri, R. Loos, D. Musser (eds.): Generic Programming '98, Proc. of a Dagstuhl Seminar, Lecture Notes on Computer Science, Vol. 1766, pp. 69-79. Springer-Verlag Berlin Heidelberg. 2000.
[Abr01]
David Abrahams. "Error and Exception Handling." Boost technical article. 2001-2003.
[Ale01a]
Andrei Alexandrescu. "An Implementation of Discriminated Unions in C++." OOPSLA 2001, Second Workshop on C++ Template Programming. Tampa Bay, 14 October 2001.
[Ale01b]
Andrei Alexandrescu. Modern C++ Design. Addison-Wesley, C++ In-Depth series. 2001.
[Ale02]
Andrei Alexandrescu. "Generic<Programming>: Discriminated Unions" series: Part 1, Part 2, Part 3. C/C++ Users Journal. 2002.
[Boo02]
Various Boost members. "Proposal --- A type-safe union." Boost public discussion. 2002.
[C++98] International Standard, Programming Languages – C++. ISO/IEC:14882. 1998.
[GoF95] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. 1995.
[Gre02]
Douglas Gregor. "BOOST_USER: variant." Boost Wiki paper. 2002.
[Gur02]
Aleksey Gurtovoy. Boost Metaprogramming Library. 2002.
[Hen01]
Kevlin Henney. Boost Any Library. 2001.
[MK02]
Paul Mensonides and Vesa Karvonen. Boost Preprocessor Library. 2002.
[MCD+01]
Steve Cleary, Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, John Maddock, Jeremy Siek. Boost Type Traits Library. 2001.
[Sut00]
Herb Sutter. Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions. Addison-Wesley, C++ In-Depth series. 2000.
[Wil02]
Anthony Williams. Double-Storage Proposal. 2002.

Part II. The BoostBook Documentation Format

The BoostBook Documentation Format

The BoostBook Documentation Format

Table of Contents
Introduction
Getting Started
Configuring local DocBook XSL and DTD distributions
Configuring Apache FOP for PostScript/PDF Output
Configuring Doxygen for Documentation Extraction
Troubleshooting
Documenting libraries
Defining a BoostBook library
From HTML to BoostBook
Sectioning in BoostBook
Bringing Together a BoostBook Document
Linking in BoostBook
Reference
BoostBook element class-specialization
BoostBook element link-test
BoostBook element link-fail-test
BoostBook element typedef
BoostBook element static-constant
BoostBook element code
BoostBook element destructor
BoostBook element template-type-parameter
BoostBook element description
BoostBook element librarylist
BoostBook element library-reference
BoostBook element boostbook
BoostBook element union
BoostBook element inherit
BoostBook element template-varargs
BoostBook element source
BoostBook element function
BoostBook element postconditions
BoostBook element compile-test
BoostBook element method
BoostBook element snippet
BoostBook element constructor
BoostBook element namespace
BoostBook element if-fails
BoostBook element free-function-group
BoostBook element functionname
BoostBook element librarycategory
BoostBook element notes
BoostBook element data-member
BoostBook element specialization
BoostBook element union-specialization
BoostBook element throws
BoostBook element template-arg
BoostBook element method-group
BoostBook element requirement
BoostBook element precondition
BoostBook element paramtype
BoostBook element using-class
BoostBook element run-test
BoostBook element librarypurpose
BoostBook element copy-assignment
BoostBook element run-fail-test
BoostBook element template
BoostBook element compile-fail-test
BoostBook element returns
BoostBook element default
BoostBook element parameter
BoostBook element signature
BoostBook element overloaded-function
BoostBook element class
BoostBook element librarycategorydef
BoostBook element type
BoostBook element enumvalue
BoostBook element overloaded-method
BoostBook element programlisting
BoostBook element complexity
BoostBook element purpose
BoostBook element template-nontype-parameter
BoostBook element library
BoostBook element librarycategorylist
BoostBook element using-namespace
BoostBook element struct-specialization
BoostBook element struct
BoostBook element lib
BoostBook element enum
BoostBook element requires
BoostBook element effects
BoostBook element libraryname
BoostBook element libraryinfo
BoostBook element testsuite
BoostBook element header
BoostBook element rationale

Introduction

Introduction

Introduction
The BoostBook documentation format is an extension of DocBook, an SGML- or XML-based format for describing documentation. BoostBook augments DocBook with semantic markup that aids in the documentation of C++ libraries, specifically the Boost C++ libraries, by providing the ability to express and refer to C++ constructs such as namespaces, classes, overloaded functions, templates, and specializations.
BoostBook offers additional features more specific to its use for documenting the Boost C++ libraries. These features are intended to eliminate or reduce the need for duplication of information and to aid in documenting portions of Boost that might otherwise not be documented. Examples of Boost-centric features include: •Testsuites: Testsuites in Boost are created by writing an appropriate Jamfile and including that Jamfile in status/Jamfile. If the testsuites are documented (as in the MultiArray library), the documentation is maintained separately from the testcase Jamfile, leading to duplication of information and the possibility of having the documentation out of sync with the Jamfile. BoostBook contains elements that describe a testsuite for both purposes: the BoostBook stylesheets can generate documentation for the testcases and also generate an appropriate Jamfile to integrate the testcases with the regression testing system.•Example programs: Example programs in documentation need to be duplicated in testcases to ensure that the examples compile and execute correctly. Keeping the two copies in sync is a tedious and error-prone task. For instance, the following code snippet persisted for six months: std::cout << f(5, 3) >> std::endl; The BoostBook format allows testcases to be generated by weaving together program fragments from example programs in the documentation. This capability is integrated with testsuite generation so that example programs are normal tests in BoostBook.•Library categorization: BoostBook contains primitives for placing libraries into categories and generating categorized and alphabetized lists of libraries.

Getting Started

Getting Started

Getting Started
To use the Boost documentation tools, you will need an XSLT processor. There are many XSLT processors available, but for now we suggest that you use xsltproc, part of libxslt. There are several ways to get libxslt, depending on your platform:
•
On Unix: Build and install libxml2 and then libxslt. Both libraries are part of the GNOME project.
•
On Windows:
•
With Cygwin, select the libxml2 and libxslt packages
•
Without Cygwin, you need a patched version of the tools available from here.
•
On MacOS X:
•
If you have Fink, just get the libxslt and doxygen packages.
Without Fink, you can download the libxslt binaries.
You will also need a recent checkout of Boost from CVS. If you would like to limit your network bandwidth or limit delays in building documentation, now might be a good time to download the DocBook DTD and XSL stylesheets as described in the section called “Configuring local DocBook XSL and DTD distributions”. You should delete or make writable the .html files in $BOOST_ROOT/doc/html before continuing.
Now we can build some documentation. Change to the directory $BOOST_ROOT/doc and run bjam --v2 to build HTML documentation. You should see several warnings like these while DocBook documentation is being built from BoostBook documentation:
Cannot find function named 'checked_delete' Cannot find function named 'checked_array_delete' Cannot find function named 'next'
These warnings are emitted when the Boost documentation tools cannot find documentation for functions, methods, or classes that are referenced in the source, and are not harmful in any way. Once Boost.Jam has completed its execution, HTML documentation for Boost will be available in $BOOST_ROOT/doc/html. You can also create HTML documentation in a single (large!) HTML file with the command line bjam --v2 onehtml, or Unix man pages with the command line bjam --v2 man. The complete list of output formats is listed in Table 1, “BoostBook Output Formats”. Several output formats can be passed to a single invocation of bjam, e.g., bjam --v2 html man docbook would generate HTML (multiple files), man pages, and DocBook documentation.
Table 1. BoostBook Output Formats

Format
Description
html
HTML output (multiple files). This is the default
onehtml
HTML output in a single HTML file.
man
Unix man pages.
pdf
PDF. Requires Apache FOP.
ps
Postscript. Requires Apache FOP.
docbook
DocBook
.
fo
XSL Formatting Objects

Configuring local DocBook XSL and DTD distributions
Configuring local DocBook XSL and DTD distributions
By default, the DocBook DTD and XSL stylesheets are accessed over a network automatically by the XSLT processor. However, these documents tend to be large and introduce a noticeable delay in the XSLT transformation step. This section describes how to configure Boost.Build to use local copies of the DocBook DTD and XSL stylesheets to improve processing time. There are a few requirements:

•
Norman Walsh's DocBook XSL stylesheets, available at the DocBook sourceforge site. Extract the DocBook XSL stylesheets to a directory on your hard disk (which we'll refer to as the DOCBOOK_XSL_DIR).
•
The DocBook DTD, available as a ZIP archive at the OASIS DocBook site. The package is called "DocBook XML 4.2". Extract the DocBook DTD to a directory on your hard disk (which we'll refer to as the DOCBOOK_DTD_DIR).
In the directory tools/build/v2 is a file named user-config.jam. Copy it to your home directory (or edit it in-place), and add a directive telling Boost.Build where to find the DocBook DTD and XSL stylesheets, replacing DOCBOOK_XSL_DIR and DOCBOOK_DTD_DIR with the paths of the DocBook XSL stylsheets and DTD, respectively:

# BoostBook configuration using boostbook : DOCBOOK_XSL_DIR : DOCBOOK_DTD_DIR ;
Future invocations of bjam will use the specified local copies of the DTD and XSL stylesheets in lieu of downloading the same sources over the network.
Configuring Apache FOP for PostScript/PDF Output
Configuring Apache FOP for PostScript/PDF Output
This section describes the steps required to configure Apache FOP to generate PostScript and PDF output for BoostBook documents. To begin, you will need two pieces of software: •A Java interpreter, available at http://java.sun.com.•Apache FOP, available at http://xml.apache.org/fop/download.html. Version 0.20.4 seems to be most stable.
Once Java is installed (we'll call Java's directory JAVA_HOME) and Apache FOP has been extracted into a directory (we'll call FOP's directory FOP_DIR), we need to configure Boost.Build to use FOP. Edit your user-config.jam or site-config.jam and add the following, replacing FOP_DIR with the directory where Apache FOP is installed, and replace JAVA_HOME with the directory where Java is installed:

using fop : FOP_DIR : JAVA_HOME ;

In some cases, JAVA_HOME is optional, but it often helps to specify it.
To test PDF generation, switch to the directory $BOOST_ROOT/doc and execute the command bjam --v2 pdf. In the absence of any errors, Apache FOP will be executed to transform the XSL:FO output of DocBook into a PDF file.
Configuring Doxygen for Documentation Extraction
Configuring Doxygen for Documentation Extraction
This section details the steps necessary to use Doxygen to extract documentation and comments from source code to build a BoostBook document (and transform it into end-user documentation). You will need a somewhat recent version of Doxygen; 1.2.18 or newer should suffice.
Boost.Build can be configured for Doxygen support by editing user-config.jam or site-config.jam to add:

using doxygen : DOXYGEN ;
DOXYGEN
should be replaced with the name of the doxygen executable (with full path name). If the right doxygen executable can be found via the path, this parameter can be omitted.
Important
The relative order of declarations in user-config.jam / site-config.jam files is significant. In particular, using doxygen line should come after the using boostbook declaration.
Generating of documentation from source files using Doxygen requires two steps. The first step involves identifying the source files so that Doxygen can process them. The second step is to specify that the output of this process, a file in the Doxygen XML format, is input for a BoostBook document. The following Jamfile.v2 illustrates a simple case of generating reference documentation for the Any library:
project boost/any/doc ; import boostbook : boostbook ; import doxygen : doxygen ;

doxygen any.doxygen : ../../../boost/any.hpp ; boostbook any : any.doxygen ;
In this example, we generate the Doxygen XML representation in the file any.doxygen from the source file ../../../boost/any.hpp by invocing Doxygen. We then use any.doxygen as a source for the BoostBook target any, which will generate documentation in any format the user requests. The actual sequence of events in this transformation is:
1.
Doxygen parses the header file ../../../boost/any.hpp and outputs a single XML file any.doxygen.
2.
The XSLT processor applies the stylesheet doxygen2boostbook.xsl to transform any.doxygen into the BoostBook file any.xml.
3.
The XSLT processor applies the stylesheet docbook.xsl to transform any.xml into the DocBook XML document any.docbook.
4.
Further transformations may generate HTML, FO, PDF, etc. from any.docbook.
Troubleshooting
Troubleshooting
The Boost documentation tools are still in their early phase of development, and some things don't work as seamlessly as we would like them to, yet. In particular, error messages can be somewhat uninformative at times. If you find yourself in the situation when you have double checked everything, and yet things still don't work as expected, consider helping the tools by deleting bin.v2 build directory.

Documenting libraries

Documenting libraries

Documenting libraries
BoostBook is an extension to DocBook, an XML format for representing documentation. BoostBook inherits much of its functionality and many elements from DocBook that are not redocumented here. When writing BoostBook documentation, please refer also to DocBook: The Definitive Guide.
Defining a BoostBook library
Defining a BoostBook library
BoostBook library documentation is contained entirely within a <library> XML element. To create a skeletal library, we need to create a new XML document (call it any.xml) that contains basic information about the library. The following BoostBook XML example describes basic information about the Boost.Any library:
Example 1. A Skeletal BoostBook Library
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <library name="Any" dirname="any" xmlns:xi="http://www.w3.org/2001/XInclude" id="any" last-revision="$Date: 2004/07/05 16:26:11 $"> <libraryinfo> <author> <firstname>Kevlin</firstname> <surname>Henney</surname> </author> <librarypurpose> Safe, generic container for single values of different value types </librarypurpose> <librarycategory name="category:data-structures"/> </libraryinfo> </library>
The first three lines identify this document as a BoostBook XML document. The DOCTYPE line states that the document conforms to the BoostBook DTD, and that the top-level element is a BoostBook <library>.
The <library> element actually describes the aspects of BoostBook library documentation. The attributes for the <library> element are:
Attributes for the <library> element
name
The full name of the library, e.g., "Any"
dirname
The name of the directory, relative to boost/libs, in which the library resides. This name may be a relative path, such as math/octonion, using "/" for the directory separator.
id
A short, unique name for the library. For libraries with simple directory names (e.g., ones that do not contain a "/"), this should be the same as the dirname. This id will be used to identify libraries and, for HTML output, will be used as the base name for the HTML file in which the library's documentation resides, so it should use only lowercase alphanumeric characters and underscores.
last-revision
Always set to $Date: 2004/07/05 16:26:11 $, which is expanded by CVS to include the date and time that the file was last modified.
Inside the <library> element we have the <libraryinfo> element, which gives information about the library itself. It contains the author's name (there may be more than one <author> element), followed by the purpose of the library and the list of categorizations. The <librarypurpose> element should always contain a very short (single sentence) description of the library's purpose, and should not terminate with a period.
The list of categories is specified by a set of <librarycategory> elements. Each <librarycategory> element has a name element that identifies one of the categories. The actual list of categories is in the file doc/src/boost.xml.
At this point, we can apply the BoostBook XSL stylesheets to any.xml (to DocBook) followed by a DocBook XSL stylesheet to generate HTML output, as described in Getting Started.
From HTML to BoostBook
From HTML to BoostBook
Most library authors are comfortable with writing HTML documentation. Writing DocBook documentation (and, by extension, BoostBook documentation) is quite similar to writing HTML, except that BoostBook uses different element names from HTML (see Table 1, “Converting HTML elements to BoostBook”) and BoostBook XML is a much more rigid format than HTML.
One of the easiest ways to convert HTML documentation into BoostBook documentation is to use HTML Tidy to transform your HTML into valid XHTML, which will make sure that all elements are properly closed, then apply the transformations in Table 1, “Converting HTML elements to BoostBook” to the body of the XHTML document. The following command uses HTML Tidy to transform HTML into valid XHTML:
tidy -asxhtml input.html > output.xhtml
When converting documentation from HTML to BoostBook, note that some redundant information that has to be manually maintained in HTML is automatically generated in BoostBook: for instance, the library categorizations, purpose, and author list described in the section called “Defining a BoostBook library” are used both in the documentation for the library and to build alphabetical and categorized lists of known libraries; similarly, tables of contents are built automatically from the titles of sections in the BoostBook document.
Table 1. Converting HTML elements to BoostBook

HTML
BoostBook
<h1>, <h2>, etc.
<section>, <title>; See the section called “Sectioning in BoostBook”
<i>, <em>
<emphasis>
<b>
<emphasis role="bold">
<ol>
<orderedlist>
<ul>
<itemizedlist>
<li>
<listitem>
<pre>
<programlisting>
<code>
<computeroutput>,<code>
<p>
<para>, <simpara>
<a>
<xref>, <link>, <ulink>;, See the section called “Linking in BoostBook”
<table>, <tr>, <th>, <td>
<table>, <informaltable>, <tgroup>, <thead>, <tfoot>, <tbody>, <row>, <entry>, <entrytbl>; BoostBook tables are equivalent to DocBook tables, for which there is a good tutorial here

Sectioning in BoostBook
Sectioning in BoostBook
"Sectioning" refers to organization of a document into separate sections, each with a title, some text, and possibly subsections. Each section is described in BoostBook via a <section> element. An introduction section may look like this:
<section id="any.intro"> <title>Introduction</title>

<para>Introduction to a library...</para>

<section> <title>A Subsection</title> <para>Subsection information...</para> </section> </section>
The <section> element contains all information that should logically be grouped within that section. The title of the section is placed within the <title> element, and any paragraphs, programs, lists, tables, or subsections can occur within the section. The id attribute of the <section> element gives a unique ID to each section, so that it may later be identified for linking. It is suggested that all IDs start with the short name of a library followed by a period, so that IDs do not conflict between libraries.

Bringing Together a BoostBook Document

Bringing Together a BoostBook Document

Bringing Together a BoostBook Document
Linking in BoostBook
Linking in BoostBook
How one links to another element in BoostBook depends greatly on the nature of the element linked and how the link should appear. There are three general linking elements: <xref>, <link>, and <ulink>. Additionally, there are linking elements for referencing specific types of entities, such as classes (<classname>), functions (<functionname>), or libraries (<libraryname>).
The <xref> element references elements that have an id attribute and a title. The actual link text is composed from title and type of the element referenced. To link to a particular ID, create an <xref> element with the linkend attribute set to the ID of the intended target. For instance, this section's ID is boostbook.linking, so we create a reference it to with <xref linkend="boostbook.linking"/>, which will look like this in the text: the section called “Linking in BoostBook”.
The <link> element references an ID in the same way as <xref>, except that <link> does not generate any text for the link, so text must be supplied within the element. For instance, we can again link to this chapter but this time specify our own text with <link linkend="boostbook.linking">like this</link>. This markup will result in a link to this chapter that looks like this.
The <ulink> element references a URL that is outside of the DocBook document. The url attribute contains the URL to link to, and the element data provides the link text.For instance, we can link to the the Boost web site with <ulink url="http://www.boost.org">Boost</ulink>, which appears in the document like this: Boost.
The <classname>, <functionname>, <methodname>, and <libraryname> link to classes, functions, methods, and libraries, respectively. The text of each element gives both the name of the element to link to and the link text. For instance, we can link to the Function library with <libraryname>Function</libraryname>, which results in the following: Function. In cases where the displayed text is different from the actual name, the alt attribute can be specified. For instance, the following XML element references the boost::function class template but displays the text function: <classname alt="boost::function">function</classname>.

Reference

Reference

Reference
Elements:•Element boostbook - Defines a BoostBook book•Element class - Declares a class or class template•Element class-specialization - A specialization (partial or full) of a class template•Element code - Mimics the code tag in HTML•Element compile-fail-test - A testcase that should fail to compile•Element compile-test - A testcase that should compile correctly•Element complexity - The time/space/etc. complexity of a function•Element constructor - Declares a constructor of the enclosing class•Element copy-assignment - Declares a copy-assignment operator•Element data-member - Declares a data member of a class•Element default - The default value of a function or template parameter•Element description - Detailed description of a construct•Element destructor - Declares a destructor for the enclosing class•Element effects - Declares the side effects of a function•Element enum - Declares an enumeration type•Element enumvalue - A single value of an enumeration•Element free-function-group - A set of functions that are grouped together under one name•Element function - Declares a function•Element functionname - References a function with the given name•Element header - Declares a C++ header with the given name•Element if-fails - What it means when a testcase fails•Element inherit - Declares a base class of the enclosing class or struct•Element lib - A library dependency•Element library - Top-level element for a library•Element library-reference - Declares the reference material for a library•Element librarycategory - Declares that the enclosing library is in this category•Element librarycategorydef - Defines a new library category•Element librarycategorylist - Categorized listing of libraries•Element libraryinfo - Provides information about a library•Element librarylist - Placeholder for an alphabetical list of libraries•Element libraryname - References a library of the given name•Element librarypurpose - Describes in one short sentence or phrase the purpose of a library•Element link-fail-test - Declares a test that should compile but fail to link•Element link-test - Declares a test that should compile and link•Element method - Declares a method, i.e., a member function•Element method-group - A set of methods that are grouped together under one name•Element namespace - Declares a namespace•Element notes - Non-normative notes about a function's semantics•Element overloaded-function - An overloaded function•Element overloaded-method - An overloaded method•Element parameter - A function parameter•Element paramtype - The type of a function parameter•Element postconditions - Conditions that must hold after the function returns•Element precondition - Conditions that must be met prior to executing a function•Element programlisting - A sample of program code•Element purpose - A short description of an entity's use•Element rationale - Describes the rationale for a particular function's design•Element requirement - A requirement/property in the Jamfile for a testcase•Element requires - Declares the requirements of a function•Element returns - Description of the return value of a function•Element run-fail-test - A testcase that should compile and link, but fail on execution•Element run-test - A testcase that should compile, link, and execute•Element signature - One signature of an overloaded function or method•Element snippet - Pulls in a code snippet from a programlisting element•Element source - Defines source code for a test•Element specialization - Defines the specialization arguments for a class specialization•Element static-constant - Declares a static constant, e.g., const int foo = 5;.•Element struct - Declares a C++ struct•Element struct-specialization - A specialization (full or partial) of a struct template•Element template - Declares the template parameters of a class or function•Element template-arg - A template argument in a specialization•Element template-nontype-parameter - A nontype template parameter•Element template-type-parameter - Declares a template type parameter•Element template-varargs - Declares a variable-length list of template parameters•Element testsuite - Describes a library testsuite•Element throws - Description of the exceptions thrown by a function•Element type - The type of an element or return type of a function•Element typedef - Declares a typedef•Element union - Declares a C++ union or union template•Element union-specialization - A specialization (full or partial) of a union template•Element using-class - Injects the method and function names of a class into the local scope•Element using-namespace - Injects the declared names from a namespace into the local scope
BoostBook element class-specialization
BoostBook element class-specialization -- A specialization (partial or full) of a class template
class-specialization
class-specialization ::= (template?, specialization?, inherit?, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element link-test
BoostBook element link-test -- Declares a test that should compile and link
link-test
link-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element link-fail-test
BoostBook element link-fail-test -- Declares a test that should compile but fail to link
link-fail-test
link-fail-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element typedef
BoostBook element typedef -- Declares a typedef
typedef
typedef ::= (type, purpose?, description?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element static-constant
BoostBook element static-constant -- Declares a static constant, e.g., const int foo = 5;.
static-constant
static-constant ::= (type, default, purpose?, description?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element code
BoostBook element code -- Mimics the code tag in HTML
code
code ::= (ANY)
Description
Description
Text within a code tag is generally typeset in a different, monospaced font so that it stands out as code. The code tag in BoostBook is transformed directly into the computeroutput tag in DocBook.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element destructor
BoostBook element destructor -- Declares a destructor for the enclosing class
destructor
destructor ::= (purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element template-type-parameter
BoostBook element template-type-parameter -- Declares a template type parameter
template-type-parameter
template-type-parameter ::= (default?, purpose?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element description
BoostBook element description -- Detailed description of a construct
description
description ::= (ANY)
Description
Description
Although the context model for this element is ANY, detailed descriptions should contain structured DocBook elements that occur within sections, e.g., paragraphs (para, simpara), lists (orderedlist, itemizedlist), tables (informaltable, table), etc.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element librarylist
BoostBook element librarylist -- Placeholder for an alphabetical list of libraries
librarylist
librarylist ::= EMPTY
Description
Description
Developers aren't generally expected to use this element. Its existence is mainly as a placeholder in boost.xml for the alphabetical list of libraries.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element library-reference
BoostBook element library-reference -- Declares the reference material for a library
library-reference
library-reference ::= (title?, section*, (header| library-reference)*)
Description
Description
Reference documentation for a library is contained with a <library-reference> element. The <library-reference> element has no attributes, and contains as children only <header> elements.
The <header> element defines a C++ header file. Within each C++ header file lie the definitions of C++ constructs to be documented. The name attribute of the <header> element gives the name of the header, as one would specify when including the header. For instance, the <library-reference> for the Any library may look like this:
<library-reference> <header name="boost/any.hpp"> <!-- C++ constructs in this header --> </header> </library-reference>
If the Any library contained multiple headers, we would list them all as children of the <library-reference> element.
library-reference
elements can be nested, so that reference material can be divided into separate sections that each contain different headers.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element boostbook
BoostBook element boostbook -- Defines a BoostBook book
boostbook
boostbook ::= (title, (chapter| library)*)
Description
Description
This element is the topmost level defined by boost.xml for all Boost documentation. It will not generally be used by developers.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element union
BoostBook element union -- Declares a C++ union or union template
union
union ::= (template?, inherit*, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element inherit
BoostBook element inherit -- Declares a base class of the enclosing class or struct
inherit
inherit ::= (ANY)
Description
Description
This element contains the name of the class inherited. The content model is free-form, as the inherited class may be an instantiation of a template and may have markup in it (e.g., classname tags).
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
access
#REQUIRED
CDATA
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element template-varargs
BoostBook element template-varargs -- Declares a variable-length list of template parameters
template-varargs
template-varargs ::= EMPTY
Description
Description
Variable-length template parameter lists are not allowed in C++, but because they are sometimes needed in documentation they are allowed in BoostBook. This element generally expands to "..." and can be used anywhere any other template parameter can be used.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element source
BoostBook element source -- Defines source code for a test
source
source ::= (#PCDATA| snippet)*
Description
Description
This element will contain the source code for a testcase that will be generated from the documentation. To reduce the amount of escaping in the text, it is recommended to use CDATA sections, which look like this:

<![CDATA[ <your program text here: no escaping needed!> ]]>
In addition to CDATA sections, code snippets can be pulled in from programlisting elements using the snippet element.
BoostBook element function
BoostBook element function -- Declares a function
function
function ::= (template?, type, parameter*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
BoostBook functions are documented by specifying the function's interface (e.g., its C++ signature) and its behavior. Constructors, destructors, member functions, and free functions all use the same documentation method, although the top-level tags differ.
The behavior of functions in BoostBook is documenting using a style similar to that of the C++ standard, with clauses describing the requirements, effects, postconditions, exception behavior, and return values of functions.
The following example illustrates some constructors and a destructor for boost::any. Note that one of the constructors takes a single parameter whose name is "other" and whose type, const any& is contained in the <paramtype> element; any number of parameters may be specified in this way.
<class name="any"> <constructor> <postconditions><para><this->empty()></para></postconditions> </constructor>

<constructor> <parameter name="other"> <paramtype>const <classname>any</classname>&amp;</paramtype> </parameter>

<effects> <simpara> Copy constructor that copies content of <code>other</code> into the new instance, so that any content is equivalent in both type and value to the content of <code>other</code>, or empty if <code>other</code> is empty. </simpara> </effects>

<throws> <simpara>May fail with a <classname>std::bad_alloc</classname> exception or any exceptions arising from the copy constructor of the contained type. </simpara> </throws> </constructor>

<destructor> <effects><simpara>Releases any and all resources used in management of instance.</simpara></effects>

<throws><simpara>Nothing.</simpara></throws> </destructor> </class>
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element postconditions
BoostBook element postconditions -- Conditions that must hold after the function returns
postconditions
postconditions ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element compile-test
BoostBook element compile-test -- A testcase that should compile correctly
compile-test
compile-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element method
BoostBook element method -- Declares a method, i.e., a member function
method
method ::= (template?, type, parameter*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
cv
#IMPLIED
CDATA
cv-qualifiers for this method, e.g., const volatile
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element snippet
BoostBook element snippet -- Pulls in a code snippet from a programlisting element
snippet
snippet ::= EMPTY
Attributes
Attributes

Name
Type
Value
Purpose
name
#REQUIRED
CDATA
The name of the programlisting element to insert

BoostBook element constructor
BoostBook element constructor -- Declares a constructor of the enclosing class
constructor
constructor ::= (template?, parameter*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element namespace
BoostBook element namespace -- Declares a namespace
namespace
namespace ::= (class| class-specialization| struct| struct-specialization| union| union-specialization| typedef| enum| free-function-group| function| overloaded-function| namespace)*
Description
Description
BoostBook namespaces are declared via the <namespace> element. As in C++, namespaces can be nested and contain other C++ constructs, such as classes or functions. The name attribute of a <namespace> element gives the namespace name (e.g., "boost"). The Any library is defined entirely within namespace boost by:
<library-reference> <header name="boost/any.hpp"> <namespace name="boost"> <!-- C++ constructs in the boost namespace --> </namespace> </header> </library-reference>
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element if-fails
BoostBook element if-fails -- What it means when a testcase fails
if-fails
if-fails ::= (ANY)
Description
Description
Describes to the user the effect a certain failing testcase will have on the usefulness of a library. This field is useful in cases where a failed testcase does not mean that the library won't be useful, but may mean that certain library features will not be available.
BoostBook element free-function-group
BoostBook element free-function-group -- A set of functions that are grouped together under one name
free-function-group
free-function-group ::= (function| overloaded-function)*
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element functionname
BoostBook element functionname -- References a function with the given name
functionname
functionname ::= (#PCDATA)
Description
Description
If a function (or overloaded function) with the given, possibly-qualified name is found, this generates a link to that function. Lookups obey currently-active using-class and using-namespace directives to aid in the search, along with searching within the current scope.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element librarycategory
BoostBook element librarycategory -- Declares that the enclosing library is in this category
librarycategory
librarycategory ::= (#PCDATA)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element notes
BoostBook element notes -- Non-normative notes about a function's semantics
notes
notes ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element data-member
BoostBook element data-member -- Declares a data member of a class
data-member
data-member ::= (type, purpose?, description?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element specialization
BoostBook element specialization -- Defines the specialization arguments for a class specialization
specialization
specialization ::= (template-arg)*
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element union-specialization
BoostBook element union-specialization -- A specialization (full or partial) of a union template
union-specialization
union-specialization ::= (template?, specialization?, inherit?, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element throws
BoostBook element throws -- Description of the exceptions thrown by a function
throws
throws ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element template-arg
BoostBook element template-arg -- A template argument in a specialization
template-arg
template-arg ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element method-group
BoostBook element method-group -- A set of methods that are grouped together under one name
method-group
method-group ::= (method| overloaded-method)*
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element requirement
BoostBook element requirement -- A requirement/property in the Jamfile for a testcase
requirement
requirement ::= (#PCDATA)
Description
Description
A requirement is part of the dependencies of a target in a Jamfile. The name attribute of a requirement element gives the name of the Boost.Build feature and the content of the requirement gives the value of that feature. A requirement such as <includes>foo.hpp would be encoded as <requirement name="includes">foo.hpp</requirement>.
Attributes
Attributes

Name
Type
Value
Purpose
name
#REQUIRED
CDATA
The name of the element being declared to referenced

BoostBook element precondition
BoostBook element precondition -- Conditions that must be met prior to executing a function
precondition
precondition ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element paramtype
BoostBook element paramtype -- The type of a function parameter
paramtype
paramtype ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element using-class
BoostBook element using-class -- Injects the method and function names of a class into the local scope
using-class
using-class ::= EMPTY
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element run-test
BoostBook element run-test -- A testcase that should compile, link, and execute
run-test
run-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element librarypurpose
BoostBook element librarypurpose -- Describes in one short sentence or phrase the purpose of a library
librarypurpose
librarypurpose ::= (#PCDATA| code| ulink| functionname| methodname| classname)*
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element copy-assignment
BoostBook element copy-assignment -- Declares a copy-assignment operator
copy-assignment
copy-assignment ::= (template?, type?, parameter*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
The return type of the copy-assignment operator does not need to be specified. If left unspecified, it will default to an unqualified reference to the enclosing class type.
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
cv
#IMPLIED
CDATA
cv-qualifiers for this method, e.g., const volatile
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element run-fail-test
BoostBook element run-fail-test -- A testcase that should compile and link, but fail on execution
run-fail-test
run-fail-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element template
BoostBook element template -- Declares the template parameters of a class or function
template
template ::= (template-type-parameter| template-nontype-parameter| template-varargs)*
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element compile-fail-test
BoostBook element compile-fail-test -- A testcase that should fail to compile
compile-fail-test
compile-fail-test ::= (source*, lib*, requirement*, purpose, if-fails?)
Attributes
Attributes

Name
Type
Value
Purpose
filename
#REQUIRED
CDATA
The name of the file associated with this element
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element returns
BoostBook element returns -- Description of the return value of a function
returns
returns ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element default
BoostBook element default -- The default value of a function or template parameter
default
default ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element parameter
BoostBook element parameter -- A function parameter
parameter
parameter ::= (paramtype, default?)
Attributes
Attributes

Name
Type
Value
Purpose
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element signature
BoostBook element signature -- One signature of an overloaded function or method
signature
signature ::= (template?, type, parameter*)
Description
Description
A signature refers to one declaration of an overloaded function or method. The signature itself has no name, because the name of the overloaded function or method is used. An overloaded function or method will have several signatures that will generally be typeset together.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
cv
#IMPLIED
CDATA
cv-qualifiers for this method, e.g., const volatile
specifiers
#IMPLIED
CDATA
The specifiers for this function, e.g., inline, static, etc.
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element overloaded-function
BoostBook element overloaded-function -- An overloaded function
overloaded-function
overloaded-function ::= (signature*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element class
BoostBook element class -- Declares a class or class template
class
class ::= (template?, inherit*, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Description
Description
C++ classes and class templates are described via the <class> element. Each class has a name (e.g., "any") given by the name attribute, a purpose given by the <purpose> element, documentation, and a set of types, functions, base classes, and data members. Here is a minimal definition of the boost::any class:
<namespace name="boost"> <class name="any"> <purpose> A class whose instances can hold instances of any type that satisfies ValueType requirements. </purpose> </class> </namespace>
Additional class documentation can be contained in a description element following the <purpose> element. This documentation will be typeset prior to documentation for specific elements in the class (e.g., constructors or methods).
Class inheritance is described via the <inherit> element. The <inherit> element requires an access attribute which must be one of public, protected, or private. The content of the <inherited> element in C++ code that names the class inherited, and may contain markup to link to the class. The following description of the class boost::bad_any_cast describes public inheritance from the class std::bad_cast. It also defines the <purpose> element, which contains a short description of the use of the class.
<class name="bad_any_cast"> <inherit access="public"><classname>std::bad_cast</classname></inherit> <purpose><para>The exception thrown in the event of a failed <functionname>any_cast</functionname> of an <classname>any</classname> value.</para></purpose> </class>
Class templates are defined by <class> elements with a <template> child element at the beginning.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element librarycategorydef
BoostBook element librarycategorydef -- Defines a new library category
librarycategorydef
librarycategorydef ::= (#PCDATA)
Description
Description
All library category definitions should be in doc/src/boost.xml, and the names of categories must be prefixed with "category:".
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element type
BoostBook element type -- The type of an element or return type of a function
type
type ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element enumvalue
BoostBook element enumvalue -- A single value of an enumeration
enumvalue
enumvalue ::= (default?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element overloaded-method
BoostBook element overloaded-method -- An overloaded method
overloaded-method
overloaded-method ::= (signature*, purpose?, description?, requires?, effects?, postconditions?, returns?, throws?, complexity?, notes?, rationale?)
Description
Description
General documentation on functions in BoostBook is provided in the function element documentation.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element programlisting
BoostBook element programlisting -- A sample of program code
programlisting
programlisting ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
name
#IMPLIED
CDATA
The name of the element being declared to referenced

BoostBook element complexity
BoostBook element complexity -- The time/space/etc. complexity of a function
complexity
complexity ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element purpose
BoostBook element purpose -- A short description of an entity's use
purpose
purpose ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element template-nontype-parameter
BoostBook element template-nontype-parameter -- A nontype template parameter
template-nontype-parameter
template-nontype-parameter ::= (type, default?, purpose?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element library
BoostBook element library -- Top-level element for a library
library
library ::= (libraryinfo, (title, ((section| library-reference| testsuite))+)?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
dirname
#REQUIRED
CDATA
url
#IMPLIED
CDATA
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes
html-only
#IMPLIED
CDATA

BoostBook element librarycategorylist
BoostBook element librarycategorylist -- Categorized listing of libraries
librarycategorylist
librarycategorylist ::= (librarycategorydef)*
Description
Description
This element is not intended for use by developers, but is used by doc/src/boost.xml as a placeholder.
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element using-namespace
BoostBook element using-namespace -- Injects the declared names from a namespace into the local scope
using-namespace
using-namespace ::= EMPTY
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element struct-specialization
BoostBook element struct-specialization -- A specialization (full or partial) of a struct template
struct-specialization
struct-specialization ::= (template?, specialization?, inherit?, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element struct
BoostBook element struct -- Declares a C++ struct
struct
struct ::= (template?, inherit*, purpose?, description?, (static-constant| typedef| enum| copy-assignment| constructor| destructor| method-group| free-function-group| function| method| overloaded-function| overloaded-method| data-member| class| class-specialization| struct| struct-specialization| union| union-specialization)*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element lib
BoostBook element lib -- A library dependency
lib
lib ::= (#PCDATA)
Description
Description
Declares a library dependency on the library named by the content of this element, to be emitted in a Jamfile.
BoostBook element enum
BoostBook element enum -- Declares an enumeration type
enum
enum ::= (enumvalue*, purpose?, description?)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element requires
BoostBook element requires -- Declares the requirements of a function
requires
requires ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element effects
BoostBook element effects -- Declares the side effects of a function
effects
effects ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element libraryname
BoostBook element libraryname -- References a library of the given name
libraryname
libraryname ::= (#PCDATA)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element libraryinfo
BoostBook element libraryinfo -- Provides information about a library
libraryinfo
libraryinfo ::= (author+, copyright*, legalnotice*, librarypurpose, librarycategory*)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element testsuite
BoostBook element testsuite -- Describes a library testsuite
testsuite
testsuite ::= ((compile-test| link-test| run-test| compile-fail-test| link-fail-test| run-fail-test)+)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element header
BoostBook element header -- Declares a C++ header with the given name
header
header ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
name
#REQUIRED
CDATA
The name of the element being declared to referenced
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

BoostBook element rationale
BoostBook element rationale -- Describes the rationale for a particular function's design
rationale
rationale ::= (ANY)
Attributes
Attributes

Name
Type
Value
Purpose
last-revision
#IMPLIED
CDATA
Set to $Date: 2004/07/05 16:26:11 $ to keep "last revised" information in sync with CVS changes
id
#IMPLIED
CDATA
A global identifier for this element
xml:base
#IMPLIED
CDATA
Implementation detail used by XIncludes

Part III. Boost.Build v2 User Manual

Boost.Build v2 User Manual

Boost.Build v2 User Manual

Table of Contents
How to use this document
Installation
Tutorial
Hello, world
Properties
Build Requests and Target Requirements
Project Attributes
Project Hierarchies
Libraries and Dependent Targets
Library dependencies
Static and shared libaries
Conditions and alternatives
Prebuilt targets
User documentation
Configuration
Writing Jamfiles
Overview
Main targets
Projects
Additional Jamfile rules
Project root
Build process
Build request
Building a main target
Building a project
Builtin target types
Programs
Libraries
Alias
Installing
Testing
Builtin features
Differences to Boost.Build V1
Configuration
Writing Jamfiles
Build process
Extender Manual
Introduction
Target types
Scanners
Tools and generators
Features
Main target rules
Toolset modules
Detailed reference
General information
Initialization
Command line
Writing Jamfiles
Generated headers
Build process
Alternative selection
Determining common properties
Features and properties
Build Variants
Property refinement
Conditional properties
Target identifiers and references
Generators
Selecting and ranking viable generators
Running generators
Selecting dependency graph
Property adjustment
Transformations cache
Frequently Asked Questions
I'm getting "Duplicate name of actual target" error. What does it mean?
Accessing environment variables
How to control properties order?
How to control the library order on Unix?
Can I get output of external program as a variable in a Jamfile?
How to get the project-root location?
How to change compilation flags for one file?
Why are the dll-path and hardcode-dll-paths properties useful?
Targets in site-config.jam
B. Boost.Build v2 architecture
Overview
The build layer
The tools layer
Targets
Dependency scanning

How to use this document

How to use this document

How to use this document
If you've just found out about Boost.Build V2 and want to know if it will work for you, start with Tutorial. You can continue with the User documentation. When you're ready to try Boost.Build in practice, go to Installation.
If you are about to use Boost.Build on your project, or already using it and have a problem, look at User documentation.
If you're trying to build a project which uses Boost.Build, look at Installation and then read about the section called “Command line”.
If you have questions, please post them to our mailing list, and be sure to indicate in the subject line that you're asking about Boost.Build V2.

Installation

Installation

Installation
This section describes how to install Boost.Build from a released source distribution. All paths are given relative to the Boost.Build v2 root directory, which is

located in the tools/build/v2 subdirectory of a full Boost distribution.
1.
Boost.Build uses Boost.Jam, an extension of the Perforce Jam portable make replacement. The recommended way to get Boost.Jam is to download a prebuilt executable from SourceForge. If a prebuilt executable is not provided for your platform or you are using Boost's sources in an unreleased state, it may be neccessary to build bjam from sources included in the Boost source tree.
2.

To install Boost.Jam, copy the executable, called bjam or bjam.exe to a location accessible in your PATH. Go to the Boost.Build root directory and run bjam --version. You should see:

Boost.Build V2 (Milestone N) Boost.Jam xx.xx.xx

where N is the version of Boost.Build you're using.
3.
Configure Boost.Build to recognize the build resources (such as compilers and libraries) you have installed on your system. Open the user-config.jam file in the Boost.Build root directory and follow the instructions there to describe your toolsets and libraries, and, if neccessary, where they are located.
4.
You should now be able to go to the example/hello/ directory and run bjam there. A simple application will be built. You can also play with other projects in the example/ directory.
If you are using Boost's CVS state, be sure to rebuild bjam even if you have a previous version. The CVS version of Boost.Build requires the CVS version of Boost.Jam.
When bjam is invoked, it always needs to be able to find the Boost.Build root directory, where the interpreted source code of Boost.Build is located. There are two ways to tell bjam about the root directory:
•
Set the environment variable BOOST_BUILD_PATH to the absolute path of the Boost.Build root directory.
•
At the root directory of your project or in any of its parent directories, create a file called boost-build.jam, with a single line:

boost-build /path/to/boost.build ;
N.B.
When bjam is invoked from anywhere in the Boost directory tree other than the Boost.Build root and its subdirectories, Boost.Build v1 is used by default. To override the default and use Boost.Build v2, you have to add the --v2 command line option to all bjam invocations.

Draft
Draft

Draft
Tutorial
Draft

Draft
Tutorial
Draft

Tutorial
Hello, world
Hello, world
The simplest project that Boost.Build can construct is stored in example/hello/ directory. The project is described by a file called Jamfile that contains:

exe hello : hello.cpp ;

Even with this simple setup, you can do some interesting things. First of all, just invoking bjam will build the debug variant of the hello executable by compiling and linking hello.cpp. Now, to build the release variant of hello, invoke

bjam release

Note that debug and release variants are created in different directories, so you can switch between variants or even build multiple variants at once, without any unneccessary recompilation. Let's extend the example by adding another line to our project's Jamfile:

exe hello2 : hello.cpp ;

Now we can build both the debug and release variants of our project:

bjam debug release

Note that two variants of hello2 are linked. Since we have already built both variants of hello, hello.cpp won't be recompiled; instead the existing object files will just be linked into the corresponding variants of hello2. Now let's remove all the built products:

bjam --clean debug release

It's also possible to build or clean specific targets. The following two commands, respectively, build or clean only the debug version of hello2.

bjam hello2 bjam --clean hello2
Properties
Properties
To portably represent aspects of target configuration such as debug and release variants, or single- and multi-threaded builds, Boost.Build uses features with associated values. For example, the "debug-symbols" feature can have a value of "on" or "off". A property is just a (feature, value) pair. When a user initiates a build, Boost.Build automatically translates the requested properties into appropriate command-line flags for invoking toolset components like compilers and linkers.
There are many built-in features that can be combined to produce arbitrary build configurations. The following command builds the project's "release" variant with inlining disabled and debug symbols enabled:

bjam release inlining=off debug-symbols=on
Properties on the command-line are specified with the syntax:

feature-name
=feature-value
The "release" and "debug" that we've seen in bjam invocations are just a shorthand way to specify values of the "variant" feature. For example, the command above could also have been written this way:

bjam variant=release inlining=off debug-symbols=on
"variant" is so commonly-used that it has been given special status as an implicit feature — Boost.Build will deduce the its identity just from the name of one of its values.
A complete description of features can be found here.
Build Requests and Target Requirements
Build Requests and Target Requirements
The set of properties specified in the command line constitute a build request — a description of the desired properties for building the requested targets (or, if no targets were explicitly requested, the project in the current directory). The actual properties used for building targets is typically a combination of the build request and properties derived from the project's Jamfiles. For example, the locations of #included header files are normally not specified on the command-line, but described in Jamfiles as target requirements and automatically combined with the build request for those targets. Multithread-enabled compilation is another example of a typical target requirement. The Jamfile fragment below illustrates how these requirements might be specified.
exe hello : hello.cpp : <include>/home/ghost/Work/boost <threading>multi ;
When hello is built, the two requirements specified above will normally always be present. If the build request given on the bjam command-line explictly contradicts a target's requirements, the command-line usually overrides (or, in the case of "free" feautures like <include> 1 See the section called “Feature Attributes”, augments) the target requirements.
Project Attributes
Project Attributes
If we want the same requirements for our other target, hello2, we could simply duplicate them. However, as projects grow, that approach leads to a great deal of repeated boilerplate in Jamfiles.

Fortunately, there's a better way. Each project (i.e. each Jamfile), can specify a set of attributes, including requirements:

project : requirements <include>/home/ghost/Work/boost <threading>multi ;

exe hello : hello.cpp ; exe hello2 : hello.cpp ;

The effect would be as if we specified the same requirement for both hello and hello2.
Project Hierarchies
Project Hierarchies
So far we've only considered examples with one project (i.e. with one Jamfile). A typical large software project would be composed of sub-projects organized into a tree. The top of the tree is called the project root. Besides a Jamfile, the project root directory contains a file called project-root.jam. Every other Jamfile in the project has a single parent project, rooted in the nearest parent directory containing a Jamfile. For example, in the following directory layout:

top/ | +-- Jamfile +-- project-root.jam | +-- src/ | | | +-- Jamfile | `-- app.cpp | `-- util/ | +-- foo/ . | . +-- Jamfile . `-- bar.cpp

the project root is top/. Because there is no Jamfile in top/util/, the projects in top/src/ and top/util/foo/ are immediate children of the root project.
Projects inherit all attributes (such as requirements) from their parents. Inherited requirements are combined with any requirements specified by the sub-project. For example, if top/Jamfile has

<include>/home/ghost/local

in its requirements, then all of its sub-projects will have it in their requirements, too. Of course, any project can add additional includes. 2 Many features will be overridden, rather than added-to, in sub-projects. See the section called “Feature Attributes” for more information More details can be found in the section on projects.
Invoking bjam without explicitly specifying any targets on the command-line builds the project rooted in the current directory. Building a project does not automatically cause its sub-projects to be built unless the parent project's Jamfile explicitly requests it. In our example, top/Jamfile might contain:

build-project src ;

which would cause the project in top/src/ to be built whenever the project in top/ is built. However, targets in top/util/foo/ will be built only if they are needed by targets in top/ or top/src/.
Libraries and Dependent Targets
Libraries and Dependent Targets
TODO: need to make this section consistent with "examples-v2/libraries".
Targets that are "needed" by other targets are called dependencies of those other targets. The targets that need the other targets are called dependent targets.
To get a feeling of target dependencies, let's continue the above example and see how src/Jamfile can use libraries from util/foo. Assume util/foo/Jamfile contains:

lib bar : bar.cpp ;

Then, to use this library in src/Jamfile, we can write:

exe app : app.cpp ../util/foo//bar ;

While app.cpp refers to a regular source file, ../util/foo//bar is a reference to another target: a library "bar" declared in the Jamfile at ../util/foo. When linking the app executable, the appropriate version of bar will be built and linked in. What do we mean by "appropriate"? For example, suppose we build "app" with:

bjam app optimization=full cxxflags=-w-8080

Which properties must be used to build foo? The answer is that some properties are propagated — Boost.Build attempts to use dependencies with the same value of propagated features. The <optimization> feature is propagated, so both "app" and "foo" will be compiled with full optimization. But <cxxflags> feature is not propagated: its value will be added as-is to compiler flags for "a.cpp", but won't affect "foo". There is still a couple of problems. First, the library probably has some headers which must be used when compiling "app.cpp". We could use requirements on "app" to add those includes, but then this work will be repeated for all programs which use "foo". A better solution is to modify util/foo/Jamfilie in this way:

project : usage-requirements <include>. ;

lib foo : foo.cpp ;

Usage requirements are requirements which are applied to dependents. In this case, <include> will be applied to all targets which use "foo" — i.e. targets which have "foo" either in sources or in dependency properties. You'd need to specify usage requirements only once, and programs which use "foo" don't have to care about include paths any longer. Or course, the path will be interpreted relatively to "util/foo" and will be adjusted according to the bjams invocation directory. For example, if building from project root, the final compiler's command line will contain -Ilib/foo.
The second problem is that we hardcode the path to library's Jamfile. Imagine it's hardcoded in 20 different places and we change the directory layout. The solution is to use project ids — symbolic names, not tied to directory layout. First, we assign a project id to Jamfile in util/foo:
project foo : usage-requirements <include>. ;
Second, we use the project id to refer to the library in src/Jamfile:

exe app : app.cpp /foo//bar ;

The "/foo//bar" syntax is used to refer to target "foo" in project with global id "/foo" (the slash is used to specify global id). This way, users of "foo" do not depend on its location, only on id, which is supposedly stable. The only thing left, it to make sure that src/Jamfile knows the project id that it uses. We add to top/Jamfile the following line:

use-project /foo : util/foo ;

Now, all projects can refer to "foo" using the symbolic name. If the library is moved somewhere, only a single line in the top-level Jamfile should be changed.
Library dependencies
Library dependencies
The previous example was simple. Often, there are long chains of dependencies between libraries. The main application is a thin wrapper on top of library with core logic, which uses library of utility functions, which uses boost filesystem library. Expressing these dependencies is straightforward:
lib utils : utils.cpp /boost/filesystem//fs ; lib core : core.cpp utils ; exe app : app.cpp core ;
So, what's the reason to even mention this case? First, because it's a bit more complex that it seems. When using shared linking, libraries are build just as written, and everything will work. However, what happens with static linking? It's not possible to include another library in static library. Boost.Build solves this problem by returning back library targets which appear as sources for static libraries. In this case, if everything is built statically, the "app" target will link not only "core" library, but also "utils" and "/boost/filesystem//fs".
So, the net result is that the above code will work for both static linking and for shared linking.
Sometimes, you want all applications in some project to link to a certain library. Putting the library in sources of all targets is possible, but verbose. You can do better by using the <source> property. For example, if "/boost/filesystem//fs" should be linked to all applications in your project, you can add <source>/boost/filesystem//fs to requirements of the project, like this:
project : requirements <source>/boost/filesystem//fs ;
Static and shared libaries
Static and shared libaries
While the previous section explained how to create and use libraries, it omitted one important detail. Libraries can be either static, which means they are included in executable files which use them, or shared (a.k.a. dynamic), which are only referred to from executables, and must be available at run time. Boost.Build can work with both types. By default, all libraries are shared. This is much more efficient in build time and space. But the need to install all libraries to some location is not always convenient, especially for debug builds. Also, if the installed shared library changes, all application which use it might start to behave differently.
Static libraries do not suffer from these problems, but considerably increase the size of application. Before describing static libraries, it's reasonable to give another, quite simple approach. If your project is built with <hardcode-dll-paths>true property, then the application will include the full paths for all shared libraries, eliminating the above problems. Unfortunately, you no longer can move shared library to a different location, which makes this option suitable only for debug builds. Further, only gcc compiler supports this option.
Building a library statically is easy. You'd need to change the value of <link> feature from it's deafault value shared, to static. So, to build everything as static libraries, you'd say
bjam link=static
on the command line. The linking mode can be fine-tuned on per-target basis.

1.
Suppose your library can be only build statically. This is easily achieved using requirements:

lib l : l.cpp : <link>static ;
2.
What if library can be both static and shared, but when using it in specific executable, you want it static? Target references are here to help:

exe important : main.cpp helpers/<link>static ;
3.
What if the library is defined in some other project, which you cannot change. But still, you want static linking to that library in all cases. You can use target references everywhere:

exe e1 : e1.cpp /other_project//bar/<link>static ; exe e10 : e10.cpp /other_project//bar/<link>static ;

but that's far from being convenient. Another way is to introduce a level of indirection: create a local target, which will refer to static version of foo. Here's the solution:

alias foo : /other_project//bar/<link>static ; exe e1 : e1.cpp foo ; exe e10 : e10.cpp foo ;

Note that the alias rule is specifically used for rename a reference to a target and possibly change the properties.

Conditions and alternatives
Conditions and alternatives
As we've just figured out, properties can significally affect the way targets are built. The processing of the <link> feature is built in the build system, and is quite complex. But there is a couple of mechanisms which allow ordinary users to do different things depending on properties.
The first mechanism is called conditinal requirement. For example, you might want to set specific defines when the library is build as shared, or you have your own define to be used in release mode. Here's a piece of Jamfile. lib network : network.cpp : <link>shared:<define>NEWORK_LIB_SHARED <variant>release:<define>EXTRA_FAST ; This will have exactly the effect we wanted: whenever <link>shared is in properties, <define>NEWORK_LIB_SHARED will be in properties as well.
Sometimes different variant of a target are so different, that describing them using conditional requirements would be hard. Imagine that a library has different sources on two supported toolsets, and dummy implementation for all the other toolset. We can express this situation using target alternatives: lib demangler : dummy_demangler.cpp ; lib demangler : demangler_gcc.cpp : <toolset>gcc ; lib demangler : demangler_msvc.cpp : <toolset>msvc ; The proper alternative will be automatically selected.
Prebuilt targets
Prebuilt targets
We've just learned how to use libraries which are created by Boost.Build. But some libraries are not. At the same time, those libraries can have different versions (release and debug, for example), that we should select depending on build properties. Prebuilt targets provide a mechanism for that. Jamfile in util/lib2 can contain:

lib lib2 : : <file>lib2_release.a <variant>release ;

lib lib2 : : <file>lib2_debug.a <variant>debug ;

This defines two alternatives for target "lib2", and for each one names a prebuilt file. Naturally, there are no sources. Instead, the <file> feature is used to specify the file name. Which alternative is selected depends on properties of dependents. If "app" binary should use "lib2", we can write:

exe app : app.cpp ../util/lib2//lib2 ;

If we build release version of "app", then it will be linked with "lib2_release.a", and debug version will use "lib2_debug.a". Another important kind of prebuilt targets are system libraries — more specifically, libraries which are automatically found by the compiler. E.g. gcc uses "-l" switch for that. Such libraries should be declared almost like regular ones:

lib zlib : : <name>z ;

We again don't specify any sources, but give a name which should be passed to the compiler. In this example, and for gcc compiler, the "-lz" option will be added. Paths where library should be searched can also be specified:

lib zlib : : <name>z <search>/opt/lib ;

And, of course, two variants can be used:

lib zlib : : <name>z <variant>release ; lib zlib : : <name>z_d <variant>debug ;

Of course, you'll probably never in your life need debug version of zlib, but for other libraries this is quite reasonable.
More advanced use of prebuilt target is described in a FAQ entry.

User documentation

User documentation

User documentation
This section will provide the information necessary to create your own projects using Boost.Build. The information provided here is relatively high-level, and detailed reference as well as the on-line help system must be used to obtain low-level documentation (see the help option).
The Boost.Build actually consists of two parts - Boost.Jam, which is a build engine with its own interpreted language, and Boost.Build itself, implemented in Boost.Jam's language. The chain of event which happen when you type "bjam" on the command is: 1.Boost.Jam tries to find Boost.Build and loads the top-level module. The exact process is described in the section on initialization 2.Boost.Build top-level module loads user-defined configuration files, "user-config.jam" and "site-config.jam", which define available toolsets.3.The Jamfile in the current directory is read. That in turn might cause reading of further Jamfiles. As a result, a tree of projects is created, with targets inside projects.4.Finally, using build request specified on the command line, Boost.Build decides which targets should be built, and how. That information is passed back to Boost.Jam, which takes care of actually running commands.
So, to be able to successfully use Boost.Build, you'd need to know only three things: • How to configure Boost.Build• How to write Jamfiles• How the build process works
Configuration
Configuration
The Boost.Build configuration is specified in the file "user-config.jam". You can edit the one which comes with Boost.Build, or create a copy in your home directory and edit that. (See the reference for the exact search paths.) The primary function of that file is to declarate which compilers and other tools are available. The simplest syntax to configure a tool is: using <tool-name> ; The "using" rule is given a name of tool, and will make that tool available to Boost.Build. For example, "using gcc ;" will make available the gcc compiler.
Since nothing but tool name is specified, Boost.Build will pick some default settings -- for example will use gcc found in path, or look in some known installation locations. For ordinary users, this is quite fine. In case you have several version of a compiler, or it's located in some unusual location, or you need to tweak the configuration, you'd need to pass additional parameters to the "using" rule. Generally, for every tool module, the parameters differ, and you can obtain the documentaiton by running bjam --help <tool-name>.init on the command line. However, for all compilers the meaning of the first three parameters is the same: version, invocation command and options.
The "version" parameter identifies the compiler, in case you have several. It can have any form you like, but it's recommended that you use a numeric identifier, like "7.1". The "invocation command" parameter is the command which must be executed to run the compiler. This might be just compiler name, or a name with a path in it. Here are some examples.
To configure a compiler installed in non-standard location and not present in path, you can do the following: using msvc : : Z:/Programs/Microsoft Visual Studio/vc98/bin/cl.exe ;
To configure several versions of a compiler, the following can be used. using gcc : 3.3 ; using gcc : 3.4 : g++-3.4 ; using gcc : 3.2 : g++-3.2 ; Note that in the first call to "using", the compiler found in path will be used, and there's no need to explicitly specify the command.
As shown above, both "version" and "invocation command" parameters are optional, but there's an important restriction: if you configure the same compiler more then once, you must pass the "version" parameter every time. For example, the following is not allowed: using gcc ; using gcc : 3.4 : g++-3.4 ; because the first "using" does not specify the version.
The options parameter is used to fine-tune the configuration. All compilers allow to pass four option, intentionally similiar in spelling to builtin features: cflags, cxxflags, compileflags and linkflags. They specify additional options which will be always passed to the corresponding tools. The cflags option applies only to the C compiler, the cxxflags option applies only to the C++ compiler and the compileflags options applies to both. For example, to use 64 bit mode with gcc you can use: using gcc : 3.4 : : <compileflags>-m64 <linkflags>-m64 ;
Writing Jamfiles
Writing Jamfiles
Overview
Overview
Jamfiles are the thing which is most important to the user, bacause they declare the targets which should be build. Jamfiles are also used for organizing targets -- each Jamfile is a separate project, which can be build independently from the other projects.
Jamfile mostly contain calls to Boost.Build functions, which do all the work, specifically: •declare main targets•define project properties•do various other things
In addition to Jamfiles, Boost.Build has another user-editable file, project-root.jam, which is mostly useful to declare constants global to all the projects. It is described in more detail below.
Main targets
Main targets
Main target
is a user-defined named entity which can be build, for example a named executable file. Declaring a main target is usually done using one of main target functions. The user can also declare custom main target function.
Most main targets rules in Boost.Build use similiar syntax:
function-name main-target-name : sources : requirements : default-build : usage-requirements ;
•
"main-target-name" is the name used to request the target on command line and to use it from other main targets. Main target name may contain alphanumeric characters and symbols '-' and '_';
•
"sources" is the list of source files and other main targets that must be combined.
•
"requirements" is the list of properties that must always be present when this main target is built.
•
"default-build" is the list of properties that will be used unless some other value of the same feature is already specified.
•
"usage-requirements" is the list of properties that will be propagated to all main targets that use this one, i.e. to all dependents.
Note that the actual requirements, default-build and usage-requirements attributes for a target are obtained by combining the explicitly specified one with those specified for the project where a target is declared.
Some main target rules have shorter list of parameters, and you should consult their documentation for details.
The list of sources specifies what should be processed to get the resulting targets. Most of the time, it's just a list of files. Sometimes, you'd want to use all files with the same extension as sources, in which case you can use the "glob" rule. Here are two examples: exe a : a.cpp ; exe b : [ glob *.cpp ] ; Unless you specify a files with absolute path, the name is considered relative to the source directory -- which is typically the same as directory when Jamfile is located, but can be changed as described here
The list of sources can also reference other main targets. The targets in the same project can be referred by using the name, and targets in other project need to specify directory or a symbolic name of the other project. For example: lib helper : helper.cpp ; exe a : a.cpp helper ; exe b : b.cpp ..//utils ; exe c : c.cpp /boost/program_options//program_opions ; The first exe uses the library defined in the same project. The second one uses some target (most likely library) defined by Jamfile one level higher. Finally, the third target uses some C++ Boost library, using the symbolic name to refer to it. More information about it can be found in tutorial and in target id reference.
Requirements are the properties that should always be present when building a target. Typically, they are includes and defines: exe hello : hello.cpp : <include>/opt/boost <define>MY_DEBUG ; In special circumstances, other properties can be used, for example if a library does not work if it's shared, or a file can't be compiled with optimization due to a compiler bug, one can use lib util : util.cpp : <link>static ; obj main : main.cpp : <optimization>off ;
Sometimes, requirements are necessary only for a specific compiler, or build variant. The conditional properties can be used in that case: lib util : util.cpp : <toolset>msvc:<link>static ; In means when whenever <toolset>msvc property is in build properties, the <link>static property will be included as well. The conditional requirements can be "chained": lib util : util.cpp : <toolset>msvc:<link>static <link>static:<define>STATIC_LINK ; will set of static link and the STATIC_LINK define on the msvc toolset.
The default-build attribute is a set of properties which should be used if build request does not specify a value. For example: exe hello : hello.cpp : : <threading>multi ; would build the target in multi-threaded mode, unless the user explicitly requests single-threaded version. The difference between requirements and default-build is that requirements cannot be overriden in any way.
A target of the same name can be declared several times. In that case is declaration is called an alternative. When the target is build, one of the alternatives will be selected and use. Alternatives need not be defined by the same main target rule. The following is OK: lib helpers : helpers.hpp ; alias helpers : helpers.lib : <toolset>msvc ;
Building of the same main target can differ greatly from platform to platform. For example, you might have different list of sources for different compilers, or different options for those compilers. Two approaches to this are explained in the tutorial.
Sometimes a main target is really needed only by some other main target. For example, a rule that declares a test-suite uses a main target that represent test, but those main targets are rarely needed by themself.
It is possible to declare target inline, i.e. the "sources" parameter may include call to other main rules. For example:
exe hello : hello.cpp [ obj helpers : helpers.cpp : <optimization>off ] ;
Will cause "helpers.cpp" to be always compiled without optimization. It's possible to request main targets declared inline, but since they are considered local, they are renamed to "parent-main-target_name..main-target-name". In the example above, to build only helpers, one should run "bjam hello..helpers".
Projects
Projects
As mentioned before, targets are grouped into project, and each Jamfile is a separate project. Projects are useful because it allows to group related targets together, define properties common to all those targets, and assign a symbolic name to the project, allowing to easily refer to the targets in the project. Two last goals are accompished with the "project" rule.
The rule has this syntax project id : <attributes> ; Here, attributes is a sequence of (attribute-name, attribute-value) pairs. The list of attribute names along with its handling is also shown in the table below. For example, it is possible to write: project tennis : requirements <threading>multi : default-build release ;
The possible attributes are listed below.
Project id
is a short way to denote a project, as opposed to the Jamfile's pathname. It is a hierarchical path, unrelated to filesystem, such as "boost/thread". Target references make use of project ids to specify a target.
Source location
specifies the directory where sources for the project are located.
Project requirements
are requirements that apply to all the targets in the projects as well as all subprojects.
Default build
is the build request that should be used when no build request is specified explicitly.
The default values for those attributes are given in the table below.

Table 1.

Attribute
Name for the 'project' rule
Default value
Handling by the 'project' rule
Project id
none
none
Assigned from the first parameter of the 'project' rule. It is assumed to denote absolute project id.
Source location
source-location
The location of jamfile for the project
Sets to the passed value
Requirements
requirements
The parent's requirements
The parent's requirements are refined with the passed requirement and the result is used as the project requirements.
Default build
default-build
none
Sets to the passed value
Build directory
build-dir
If parent has a build dir set, the value of it, joined with the relative path from parent to the current project. Otherwise, empty
Sets to the passed value, interpreted as relative to the project's location.

Additional Jamfile rules
Additional Jamfile rules
There's a number of other helper rules which can be used in Jamfile, described in the following table.
Table 2.

Rule
Semantic
project
Define project attributes.
use-project
Make another project known.
build-project
Build another project when this one is built.
explicit
States that the target should be built only by explicit request.
glob
Takes a list of wildcards, and returns the list of files which match any of the wildcards.

Project root
Project root
Each project is also associated with project root. That's a root for a tree of projects, which specifies some global properties.
Project root for a projects is the nearest parent directory which contains a file called project-root.jam. That file defines certain properties which apply to all projects under project root. It can:

•
configure toolsets, via call to toolset.using
•
refer to other projects, via the use-project rule
•
declare constants, via the constant and path-constant rules.
To facilitate declaration of simple projects, Jamfile and project-root can be merged together. To achieve this effect, the project root file should call the project rule. The semantic is precisely the same as if the call was made in Jamfile, except that project-root.jam will start to serve as Jamfile. The Jamfile in the directory of project-root.jam will be ignored, and project-root.jam will be able to declare main targets as usual.
Build process
Build process
When you've described your targets, you want Boost.Build to run the right tools and create the needed targets. This section will describe two things: how you specify what to build, and how the main targets are actually constructed.
The most important thing to note is that in Boost.Build, unlike other build tools, the targets you declare do not correspond to specific files. What you declare in Jamfiles is more like "metatarget". Depending on the properties that you specify on the command line, each "metatarget" will produce a set of real targets corresponding to the requested properties. It is quite possible that the same metatarget is build several times with different properties, and will, of course, produce different files.
Tip
This means that for Boost.Build, you cannot directly obtain build variant from Jamfile. There could be several variants requested by the user, and each target can be build with different properties.
Build request
Build request
The command line specifies which targets to build and with what properties. For example: bjam app1 lib1//lib1 toolset=gcc variant=debug optimization=full would build two targets, "app1" and "lib1//lib1" with the specified properties. You can refer to any targets, using target id and specify arbitrary properties. Some of the properties are very common, and for them the name of the property can be omitted. For example, the above can be written as: bjam app1 lib1//lib1 gcc debug optimization=full The complete syntax which has some additional shortcuts if described here.
Building a main target
Building a main target
When you request, directly or indirectly, a build of a main target with specific requirements, the following steps are made. Some brief explanation is provided, and more detailes are given in the reference. 1.Applying default build. If the default-build property of a target specifies a value of a feature which is not present in the build request, that value is added.2.Selecting the main target alternative to use. For each alternative we look how many properties are present both in alternative's requirements, and in build request. The alternative with large number of matching properties is selected. 3.Determining "common" properties. The build request is refined with target's requirements. The conditional properties in requirements are handled as well. Finally, default values of features are added. 4.Building targets referred by the sources list and dependency properties. The list of sources and the properties can refer to other target using target references. For each reference, we take all propagated properties, refine them by explicit properties specified in the target reference, and pass the resulting properties as build request to the other target. 5.Adding the usage requirements produces when building dependencies to the "common" properties. When dependencies are built in the previous step, they return both the set of created "real" targets, and usage requirements. The usage requirements are added to the common properties and the resulting property set will be used for building the current target. 6.Building the target using generators. To convert the sources to the desired type, Boost.Build uses "generators" --- objects which correspond to tools like compilers and linkers. Each generator declares what type of targets in can produce and what type of sources it requires. Using this information, Boost.Build determines which generators must be run to produce a specific target from specific sources. When generators are run, they return the "real" targets. 7.Computing the usage requirements to be returned. The conditional properties in usage requirements are expanded and the result is returned.
Building a project
Building a project
Often, user request a build of a complete project, not just one main target. In fact, invoking bjam without parameters builds the project defined in the current directory.
When a project is build, the build request is passed without modification to all main targets in that project. It's is possible to prevent implicit building of a target in a project with the explicit rule: explicit hello_test ; would cause the hello_test target to be built only if explicitly requested by the user or by some other target.
The Jamfile for a project can include a number of build-project rule calls, that specify additional projects to be built.
Builtin target types
Builtin target types
Programs
Programs
Programs are created using the exe rule, which follows the common syntax. For example: exe hello : hello.cpp some_library.lib /some_project//library : <threading>multi ; This will create an executable file from the sources -- in this case, one C++ file, one library file present in the same directory, and another library which is created by Boost.Build. Generally, sources can include C and C++ files, object files and libraries. Boost.Build will automatically try to convert targets of other types.
Tip
On Windows, if an application uses dynamic libraries, and both the application and the libraries are built by Boost.Build, its not possible to immediately run the application, because the PATH environment variable should include the path to the libraries. It means you have to either add the paths manually, or place the application and the libraries to the same directory, for example using the stage rule.
Libraries
Libraries
Libraries are created using the lib rule, which follows the common syntax. For example: lib helpers : helpers.cpp : <include>boost : : <include>. ;
In the most common case, the lib creates a library from the specified sources. Depending on the value of <link> feature the library will be either static or shared. There are two other cases. First is when the library is installed somewhere in compiler's search paths, and should be searched by the compiler (typically, using the -l option). The second case is where the library is available as a prebuilt file and the full path is known.
The syntax for these case is given below: lib z : : <name>z <search>/home/ghost ; lib compress : : <file>/opt/libs/compress.a ; The name property specifies the name which should be passed to the -l option, and the file property specifies the file location. The search feature specifies paths where the library should be searched. That feature can be specified several time, or can be omitted -- in which case only default compiler paths will be searched.
The difference between using the file feature as opposed to the name name feature together with the search feature is that file is more precise. A specific file will be used. On the other hand, the search feature only adds a library path, and the name feature gives the basic name of the library. The search rules are specific to the linker. For example, given these definition: lib a : : <variant>release <file>/pool/release/a.so ; lib a : : <variant>debug <file>/pool/debug/a.so ; lib b : : <variant>release <file>/pool/release/b.so ; lib b : : <variant>debug <file>/pool/debug/b.so ; It's possible to use release version of a and debug version of b. Had we used the name and search features, the linker would always pick either release or debug versions.
For convenience, the following syntax is allowed: lib z ; lib gui db aux ; and is does exactly the same as: lib z : : <name>z ; lib giu : : <name>gui ; lib db : : <name>db ; lib aux : : <name>aux ;
When a library uses another library you should put that another library in the list of sources. This will do the right thing in all cases. For portability, you should specify library dependencies even for searched and prebuilt libraries, othewise, static linking on Unix won't work. For example: lib z ; lib png : z : <name>png ;
Note
When a library (say, a), which has another library, (say, b) is linked dynamically, the b library will be incorporated in a. (If b is dynamic library as well, then a will only refer to it, and not include any extra code.) When the a library is linked statically, Boost.Build will assure that all executables which link to a will also link to b.
One feature of Boost.Build which is very important for libraries is usage requirements. For example, if you write: lib helpers : helpers.cpp : : : <include>. ; then compiler include path for all targets which use helpers will contain the directory where the target is defined.path to "helpers.cpp". So, the user need only to add helpers to the list of sources, and don't bother about other requirements. This allows to greatly simplify Jamfiles.
Note
If you don't want shared libraries to include all libraries which are specified in sources (especially statically linked ones), you'd need to use the following: lib b : a.cpp ; lib a : a.cpp : <use>b : : <library>b ; This specifies that a uses b, and causes all executables which link to a also link to b. In this case, even for shared linking, the a library won't even refer to b.
Alias
Alias
The alias rule follows the common syntax. For example: alias core : im reader writer ; will build the sources and return the generated source targets without modification.
The alias rule is a convenience tool. If you often build the same group of targets at the same time, you can define the alias to save typing.
Another use of the alias rule is to change build properties. For example, if you always want static linking for a specific C++ Boost library, you can write the following: alias boost_thread : /boost/thread//boost_thread : <link>static ; and use only the boost_thread alias in your Jamfiles.
It is also allowed to specify usage requirements for the alias target. If you write the following: alias header_only_library : : : : <include>/usr/include/header_only_library ; then using header_only_library in sources will only add an include path. Also note that when there are some sources, their usage requirements are propagated, too. For example: lib lib : lib.cpp : : : <include>. ; alias lib_alias ; exe main : main.cpp lib_alias ; will compile main.cpp with the additional include.
Installing
Installing
For installing the built target you should use the stage rule follows the common syntax. For example: stage dist : hello helpers ; will cause the targets hello and helpers to be moved to the dist directory. The directory can be changed with the location property: stage dist : hello helpers : <location>/usr/bin ;
Specifying the names of all libraries to install can be boring. The stage allows to specify only the top-level executable targets to install, and automatically install all dependencies: stage dist : hello : <traverse-dependencies>on <include-type>EXE <include-type>LIB ; will find all targets that hello depends on, and install all of the which are either executables or libraries.
Testing
Testing
Boost.Build has convenient support for running unit tests. The simplest way is the unit-test rule, which follows the common syntax. For example: unit-test helpers_test : helpers_test.cpp helpers ;
The unit-test rule behaves like the exe rule, but after the executable is created it is run. If the executable returns error, the build system will also return error and will try running the executable on the next invocation until it runs successfully. This behaviour ensures that you can't miss a unit test failure.
There are rules for more elaborate testing: compile, compile-fail, run and run-fail. They are more suitable for automated testing, and are not covered here yet.
Builtin features
Builtin features
variant
The feature which combines several low-level features in order to make building most common variants simple.
Allowed values:
debug
, release, profile
The value debug expands to
<optimization>off <debug-symbols>on <inlining>off <runtime-debugging>on
The value release expands to
<optimization>speed <debug-symbols>off <inlining>full <runtime-debugging>off
The value profile expands to the same as release, plus:
<profiling>on <debug-symbols>on
Rationale:
Runtime debugging is on in debug build to suit expectations of people used various IDEs. It's assumed other folks don't have any specific expectation in this point.
link
Feature which controls how libraries are built.
Allowed values:
shared
, static
source
Tthe <source>X feature has the same effect on building a target as putting X in the list of sources. The feature is sometimes more convenient: you can put <source>X in the requirements for a project and it will be linked to all executables.
library
This feature is equivalent to the <source> feature, and exists for backward compatibility reasons.
use
Causes the target referenced by the value of this feature to be constructed and adds it's usage requirements to build properties. The constructed targets are not used in any other way. The primary use case is when you use some library and want it's usage requirements (such as include paths) to be applied, but don't want to link to the library.
dll-path
Specify an additional path where shared libraries should be searched where the executable or shared library is run. This feature only affect Unix compilers. Plase see the FAQ entry for details.
hardcode-dll-paths
Controls automatic generation of dll-path properties.
Allowed values:
true
, false. This property is specific to Unix systems. If an executable is build with <hardcode-dll-paths>true, the generated binary will contain the list of all the paths to the used shared libraries. As the result, the executable can be run without changing system paths to shared libraries, or installing the libraries to system paths. This is very convenient during development. Plase see the FAQ entry for details.
Differences to Boost.Build V1
Differences to Boost.Build V1
While Boost.Build V2 is based on the same ideas as Boost.Build V1, some of the syntax was changed, and some new important features were added. This chapter describes most of the changes.
Configuration
Configuration
In V1, there were two methods to configure a toolset. One is to set some environment variable, or use "-s" command line option to set variable inside BJam. Another method was creating new toolset module, which would set the variables and then invoke basic toolset. Neither method is necessary now, the "using" rule provides a consistent way to initialize toolset, including several versions. See section on configuraton for details.
Writing Jamfiles
Writing Jamfiles
Probably one of the most important differences in V2 Jamfiles is the project requirements. In V1, if several targets have the same requirements (for example, common include path), it was necessary to manually write that requirements, or use a helper rule. In V2, the common properties can be specified with the "requirements" project attribute, as documented here.
The usage requirements is also important mechanism to simplify Jamfile. If a library requires all clients to use specific includes, or macros when compiling the code which depends on the library, this information can be cleanly represented.
The difference between "lib" and "dll" targets in V1 is completely eliminated in V2. There's only one target -- "lib", which can create either static or shared library depending on the value of the <link> feature. If your target should be only build in one variant, you can add <link>shared or <link>static to requirements.
The syntax for referring to other targets was changed a bit. While in V1 one would use: exe a : a.cpp <lib>../foo/bar ; the V2 syntax is: exe a : a.cpp ../foo//bar ; Note that you don't need to specify the type of other target, but the last element should be separated to double slash, to indicate that you're referring to target "bar" in project "../foo", and not to project "../foo/bar".
Build process
Build process
The command line syntax in V2 is completely different. For example bjam -sTOOLS=msvc -sBUILD=release some_target now becomes: bjam toolset=msvc variant=release some_target or, using shortcuts, just: bjam msvc release some_target See the reference for complete description of the syntax.

Extender Manual

Extender Manual

Extender Manual
Introduction
Introduction
This document explains how to extend Boost.Build to accomodate your local requirements. Let's start with quite simple, but realistic example.
Say you're writing an application which generates C++ code. If you ever did this, you know that it's not nice. Embedding large portions of C++ code in string literals is very awkward. A much better solution is:
1.
Write the template of the code to be generated, leaving placeholders at the points which will change
2.
Access the template in your application and replace placeholders with appropriate text.
3.
Write the result.
It's quite easy to achieve. You write special verbatim files, which are just C++, except that the very first line of the file gives a name of variable that should be generated. A simple tool is created which takes verbatim file and creates a cpp file with a single char* variable, which name is taken from the first line of verbatim file, and which value is properly quoted content of the verbatim file.
Let's see what Boost.Build can do.
First off, Boost.Build has no idea about "verbatim files". So, you must register a new type. The following code does it:
import type ; type.register VERBATIM : verbatim ;
The first parameter to 'type.register' gives the name of declared type. By convention, it's uppercase. The second parameter is suffix for this type. So, if Boost.Build sees "code.verbatim" in the list of sources, it knows that it's of type VERBATIM.
Lastly, you need a tool to convert verbatim files to C++. Say you've sketched such a tool in Python. Then, you have to inform Boost.Build about the tool. The Boost.Build concept which represents a tool is generator.
First, you say that generator 'inline-file' is able to convert VERBATIM type into C++:
import generators ; generators.register-standard verbatim.inline-file : VERBATIM : CPP ;
Second, you must specify the commands to be run to actually perform convertion:
actions inline-file { "./inline-file.py" $(<) $(>) }
Now, we're ready to tie it all together. Put all the code above in file "verbatim.jam", add "import verbatim ;" to "project-root.jam", and it's possible to write the following in Jamfile:
exe codegen : codegen.cpp class_template.verbatim usage.verbatim ;
The verbatim files will be automatically converted into C++ and linked it.
In the subsequent sections, we will extend this example, and review all the mechanisms in detail. The complete code is available in example/customization directory.
Target types
Target types
The first thing we did in the intruduction was declaring a new target type: import type ; type.register VERBATIM : verbatim ; The type is the most important property of a target. Boost.Build can automatically generate necessary build actions only because you specify the desired type (using the different main target rules), and because Boost.Build can guess the type of sources from their extensions.
The first two parameters for the type.register rule are the name of new type and the list of extensions associated with it. A file with an extension from the list will have the given target type. In the case where a target of the declared type is generated from other sources, the first specified extension will be used. This behaviour can be changed using the type.set-generated-target-suffix rule.
Something about 'main' types.
Something about base types.
Scanners
Scanners
Sometimes, a file can refer to other files via some include mechanism. To make Boost.Build track dependencies to the included files, you need to provide a scanner. The primary limitation is that only one scanner can be assigned to a target type.
First, we need to declare a new class for the scanner: class verbatim-scanner : common-scanner { rule pattern ( ) { return "//###include[ ]*\"([^\"]*)\"" ; } } All the complex logic is in the common-scanner class, and you only need to override the method which returns the regular expression to be used for scanning. The paranthethis in the regular expression indicate which part of the string is the name of the included file.
After that, we need to register our scanner class: scanner.register verbatim-scanner : include ; The value of the second parameter, in this case include, specifies which properties contain the list of paths which should be searched for the included files.
Finally, we assign the new scaner to the VERBATIM target type: type.set-scanner VERBATIM : verbatim-scanner ; That's enough for scanning include dependencies.
Tools and generators
Tools and generators
This section will describe how Boost.Build can be extended to support new tools.
For each additional tool, a Boost.Build object called generator must be created. That object has specific types of targets which it accepts an produces. Using that information, Boost.Build is able to automatically invoke the generator. For example, if you declare a generator which takes a target of the type D and produces a target of the type OBJ, when placing a file with extention .d in a list of sources will cause Boost.Build to invoke your generator, and then to link the resulting object file into an application. (Of course, this requires that you specify that the .d extension corresponds to the D type.)
Each generator should be an instance of a class derived from the generator class. In the simplest case, you don't need to create a derived class, but simply create an instance of the generator class. Let's review the example we've seen in the introduction. import generators ; generators.register-standard verbatim.inline-file : VERBATIM : CPP ; actions inline-file { "./inline-file.py" $(<) $(>) }
We declare a standard generator, specifying its id, the source type and the target type. When invoked, the generator will create a target of type CPP which will have the source target of type VERBATIM as the only source. But what command will be used to actually generate the file? In bjam, actions are specified using named "actions" blocks and the name of the action block should be specified when creating targets. By convention, generators use the same name of the action block as their own id. So, in above example, the "inline-file" actions block will be use to convert the source into the target.
There are two primary kinds of generators: standard and composing, which are registered with the generators.register-standard and the generators.register-composing rules, respectively. For example: generators.register-standard verbatim.inline-file : VERBATIM : CPP ; generators.register-composing mex.mex : CPP LIB : MEX ; The first generators takes a single source of type VERBATIM and produces a result. The second generator takes any number of sources, which can have either the CPP or the LIB type. Composing generators are typically used for generating top-level target type. For example, the first generator invoked when building an exe target is a composing generator corresponding to the proper linker.
You should also know about two specific function for registering generators: generators.register-c-compiler and generators.register-linker. The first sets up header dependecy scanning for C files, and the seconds handles various complexities like searched libraries. For that reason, you should always use those functions when adding support for compilers and linkers.
(Need a note about UNIX)
Custom generator classes
Custom generator classes
The standard generators allows you to specify source and target types, action, and a set of flags. If you need anything more complex, you need to create a new generator class with your own logic. Then, you have to create an instance of that class and register it. Here's an example how you can create your own generator class: class custom-generator : generator { rule __init__ ( * : * ) { generator.__init__ $(1) : $(2) : $(3) : $(4) : $(5) : $(6) : $(7) : $(8) : $(9) ; } } generators.register [ new custom-generator verbatim.inline-file : VERBATIM : CPP ] ; This generator will work exactly like the verbatim.inline-file generator we've defined above, but it's possible to customize the behaviour by overriding methods of the generator class.
There are two methods of interest. The run methods is responsible for overall process - it takes a number of source targets, converts them the the right types, and creates the result. The generated-targets method is called when all sources are converted to the right types to actually create the result.
The generated-target method can be overridden when you want to add additional properties to the generated targets or use additional sources. For example (which is real), you have a tool for analysing programs, which should be given a name of executable and the list of all sources. Naturally, you don't want to list all source files manually. Here's how the generated-target method can find the list of sources automatically: class itrace-generator : generator { .... rule generated-targets ( sources + : property-set : project name ? ) { local leafs ; local temp = [ virtual-target.traverse $(sources[1]) : : include-sources ] ; for local t in $(temp) { if ! [ $(t).action ] { leafs += $(t) ; } } return [ generator.generated-targets $(sources) $(leafs) : $(property-set) : $(project) $(name) ] ; } } generators.register [ new itrace-generator nm.itrace : EXE : ITRACE ] ; The generated-targets rule will be called with a single source target of type EXE. The call to the virtual-target.traverse will return all targets the executable depends on, and we further find files which are not produced from anything. The found targets are added to the sources.
The run method can be overriden to completely customize the way generator works. In particular, the conversion of sources to the desired types can be completely customized. Here's another real example. Tests for the Boost Python library usually consist of two parts: a Python program and a C++ file. The C++ file is compiled to Python extension which is loaded by the Python program. But in the likely case that both files have the same name, the created Python extension must be renamed. Otherwise, Python program will import itself, not the extension. Here's how it can be done: rule run ( project name ? : property-set : sources * : multiple ? ) { local python ; for local s in $(sources) { if [ $(s).type ] = PY { python = $(s) ; } } local libs ; for local s in $(sources) { if [ type.is-derived [ $(s).type ] LIB ] { libs += $(s) ; } } local new-sources ; for local s in $(sources) { if [ type.is-derived [ $(s).type ] CPP ] { local name = [ $(s).name ] ; if $(name) = [ $(python).name ] { name = $(name)_ext ; } new-sources += [ generators.construct $(project) $(name) : PYTHON_EXTENSION : $(property-set) : $(s) $(libs) ] ; } } result = [ construct-result $(python) $(new-sources) : $(project) $(name) : $(property-set) ] ; } First, we separate all source into python files, libraries and C++ sources. For each C++ source we create a separate Python extension by calling generators.construct and passing the C++ source and the libraries. At this point, we also change the extension's name, if necessary.
Features
Features
Often, we need to control the options passed the invoked tools. This is done with features. Consider an example: # Declare a new feature import feature : feature ; feature verbatim-options : : free ; # Cause the value of the 'verbatim-options' feature to be # available as 'OPTIONS' variable inside verbatim.inline-file import toolset : flags ; flags verbatim.inline-file OPTIONS <verbatim-options> ; # Use the "OPTIONS" variable actions inline-file { "./inline-file.py" $(OPTIONS) $(<) $(>) } We first define a new feature. Then, the flags invocation says that whenever verbatin.inline-file action is run, the value of the verbatim-options feature will be added to the OPTIONS variable, an can be used inside the action body. You'd need to consult online help (--help) to find all the features of the toolset.flags rule.
Although you can define any set of features and interpret their values in any way, Boost.Build suggests the following coding standard for designing features.
Most features should have a fixed set of values, which is portable (tool neutral) across the class of tools they are designed to work with. The user does not have to adjust the values for a exact tool. For example, <optimization>speed has the same meaning for all C++ compilers and the user does not have to worry about the exact options which are passed to the compiler's command line.
Besides such portable features there are special 'raw' features which allow the user to pass any value to the command line parameters for a particular tool, if so desired. For example, the <cxxflags> feature allows to pass any command line options to a C++ compiler. The <include> feature allows to pass any value to the -I and the interpretation is tool-specific. (There an example of very smart usage of that feature). Of course one should always strive to use the portable features but these should still be provided as a backdoor just to make sure Boost.Build does not take away any control from the user.
Some of the reasons why portable features are better are: •Since a portable feature have a fixed set of value, you will be able to build your project with two different settings of the feature. Boost.Build will automatically use two different directories for produced files. If you pass raw compiler options, Boost.Build assumes you know what you are doing, and would not care about what options are passed. •Unlike "raw" features, you don't need to use specific compiler flags in Jamfile, and it will more likely work on other systems.
Steps for adding a feauture
Steps for adding a feauture
Adding a feature requires three steps:

1.
Declaring a feature. For that, the "feature.feature" rule is used. You should have to decide on the set of feature attributes:

•
if feature has several values, and significally affects build, make it "propagated", so that whole project is build with the same value by default
•
if a feature does not have a fixed list of values, it must be "free".
•
if feature is used to refer to a path, it must be "path".
•
if feature is used to refer to some target, it must be "dependency".
2.
Converting the feature value into variable. To use feature in build action, it must be converted into a variable, accessible in build action. This is accomplished by "toolset.flags" rule.
3.
Using the variable. The variable set in step 2 can be used in build action to form command parameters or files.
Another example
Another example
Here's an another example. Let's see how we can make a feature which refers to a target. For example, when linking dynamic libraries on windows, one sometimes needs to specify "DEF file", telling what functions should be exported. It would be nice to use this file like this: lib a : a.cpp : <def-file>a.def ; Actually, this feature is already supported, but anyway...
1.
Since the feature refers to a target, it must be "dependency". feature def-file : : free dependency ;
2.
One of the toolsets which cares about DEF files is msvc. The following line should be added to it.

flags msvc.link DEF_FILE <def-file> ;
3.
Since the DEF_FILE variable is not used by the msvc.link action, we need to modify it to be:

actions link bind DEF_FILE { $(.LD) .... /DEF:$(DEF_FILE) .... }
Note the "bind DEF_FILE" part. It tells bjam that DEF_FILE refers to a file, otherwise the variable will contain internal target name, which is not likely to make sense for the linker.
We've almost done, but should stop for a small workaround. Add the following code to msvc.jam

rule link { DEPENDS $(<) : [ on $(<) return $(DEF_FILE) ] ; }

This is needed to accomodate some bug in bjam, which hopefully will be fixed one day.
Variants and composite features.
Variants and composite features.
Sometimes you want to create a shorcut for some set of features. For example, release is a value of the variant and is a shortcut for a set of features.
.

It is possible to define your build variants. For example: variant crazy : <optimization>speed <inlining>off <debug-symbols>on <profiling>on ; will define a new variant with the specified set of properties. You can also extend an existing variant: variant super_release : release : <define>USE_ASM ; In this case, super_release will expand to all properties specified by release, and the additional one you've specified.
You are not restricted to using the variant feature only. Here's example which defines a brand new feature: feature parallelism : mpi fake none : composite link-incompatible ; feature.compose <parallelism>mpi : <library>/mpi//mpi/<parallelism>none ; feature.compose <parallelism>fake : <library>/mpi//fake/<parallelism>none ; This will allow you to specify value of feature parallelism, which will expand to link to the necessary library.
Main target rules
Main target rules
The main target rule is what creates a top-level target, for example "exe" or "lib". It's quite likely that you'll want to declare your own and there are as many as three ways to do that.
The first is the simplest, but is sufficient in a number of cases. Just write a wrapper rule, which will redirect to any of the existing rules. For example, you have only one library per directory and want all cpp files in the directory to be compiled. You can achieve this effect with: lib codegen : [ glob *.cpp ] ; but what if you want to make it even simple. Then, you add the following definition to the project-root.jam file: rule glib ( name : extra-sources * : requirements * ) { lib $(name) : [ glob *.cpp ] $(extra-sources) : $(requirements) ; } which would allow to reduce Jamfile to glib codegen ;
The second approach is suitable when your target rule should just produce a target of specific type. Then, when declaring a type you should tell Boost.Build that a main target rule should be created. For example, if you create a module "obfuscate.jam" containing:

import type ; type.register OBFUSCATED_CPP : ocpp : : main ;

import generators ; generators.register-standard obfuscate.file : CPP : OBFUSCATED_CPP ;
and import that module, you'll be able to use the rule "obfuscated-cpp" in Jamfiles, which will convert source to the OBFUSCATED_CPP type.
The remaining method is to declare your own main target class. The simplest example of this can be found in "build/alias.jam" file. The current V2 uses this method when transformations are relatively complex. However, we might deprecate this approach. If you find that you need to use it (that is, the first two approaches are not sufficient), please let us know by posting to the mailing list.
Toolset modules
Toolset modules
If your extensions will be used only on one project, they can be placed in a separate .jam file which will be imported by your project-root.jam. If the extensions will be used on many projects, the users will thank you for a finishing touch.
The standard way to use a tool in Boost.Build is the using rule. To make it work, you module should provide an init rule. The rule will be called with the same parameters which were passed to the using rule. The set of allowed parameters is determined by you. For example, you can allow the user to specify paths, tool version, or tool options.
Here are some guidelines which help to make Boost.Build more consistent: •The init rule should never fail. Even if user provided a wrong path, you should emit a warning and go on. Configuration may be shared between different machines, and wrong values on one machine can be OK on another. •Prefer specifying command to be executed to specifying path. First of all, this gives more control: it's possible to specify /usr/bin/g++-snapshot time g++ as the command. Second, while some tools have a logical "installation root", it better if user don't have to remember if a specific tool requires a full command or a path. •Check for multiple initialization. A user can try to initialize the module several times. You need to check for this and decide what to do. Typically, unless you support several versions of a tool, duplicate initialization is a user error. If tool version can be specified during initialization, make sure the version is either always specified, or never specified (in which case the tool is initialied only once). For example, if you allow: using yfc ; using yfc : 3.3 ; using yfc : 3.4 ; Then it's not clear if the first initialization corresponds to version 3.3 of the tool, version 3.4 of the tool, or some other version. This can lead to building twice with the same version. •If possible, the init must be callable with no parameters. In which case, it should try to autodetect all the necessary information, for example, by looking for a tool in PATH or in common installation locations. Often this is possible and allows the user to simply write: using yfc ; •Consider using facilities in the tools/common module. You can take a look at how tools/gcc.jam uses that module in the init rule.

Detailed reference

Detailed reference

Detailed reference
General information
General information
Initialization
Initialization
bjam's first job upon startup is to load the Jam code which implements the build system. To do this, it searches for a file called "boost-build.jam", first in the invocation directory, then in its parent and so forth up to the filesystem root, and finally in the directories specified by the environment variable BOOST_BUILD_PATH. When found, the file is interpreted, and should specify the build system location by calling the boost-build rule:
rule boost-build ( location ? )
If location is a relative path, it is treated as relative to the directory of boost-build.jam. The directory specified by location and directories in BOOST_BUILD_PATH are then searched for a file called bootstrap.jam which is interpreted and is expected to bootstrap the build system. This arrangement allows the build system to work without any command-line or environment variable settings. For example, if the build system files were located in a directory "build-system/" at your project root, you might place a boost-build.jam at the project root containing:

boost-build build-system ;

In this case, running bjam anywhere in the project tree will automatically find the build system.
The default "bootstrap.jam", after loading some standard definitions, loads two files, which can be provided/customised by user: "site-config.jam" and "user-config.jam".
Locations where those files a search are summarized below:
Table 1. Search paths for configuration files

site-config.jam
user-config.jam
Linux
/etc
$HOME
$BOOST_BUILD_PATH
$HOME
$BOOST_BUILD_PATH
Windows
$SystemRoot
$HOME
$BOOST_BUILD_PATH
$HOME
$BOOST_BUILD_PATH

Boost.Build comes with default versions of those files, which can serve as templates for customized versions.
Command line
Command line
The command line may contain:
•
Jam options,
•
Boost.Build options,
•
Command line arguments
Command line arguments
Command line arguments specify targets and build request using the following rules.
•
An argument which does not contain slashes or the "=" symbol is either a value of an implicit feature, or target to be built. It is taken to be value of a feature if appropriate feature exists. Otherwise, it is considered a target id. Special target name "clean" has the same effect as "--clean" option.
•
An argument with either slashes or the "=" symbol specifies a number of build request elements. In the simplest form, it's just a set of properties, separated by slashes, which become a single build request element, for example:

borland/<runtime-link>static

More complex form is used to save typing. For example, instead of

borland/runtime-link=static borland/runtime-link=dynamic

one can use

borland/runtime-link=static,dynamic

Exactly, the conversion from argument to build request elements is performed by (1) splitting the argument at each slash, (2) converting each split part into a set of properties and (3) taking all possible combination of the property sets. Each split part should have the either the form

feature-name
=feature-value1[","feature-valueN]*

or, in case of implicit feature

feature-value1
[","feature-valueN;]*

and will be converted into property set

<feature-name>feature-value1 .... <feature-name>feature-valueN
For example, the command line

target1 debug gcc/runtime-link=dynamic,static

would cause target called target1 to be rebuilt in debug mode, except that for gcc, both dynamically and statically linked binaries would be created.
Command line options
All of the Boost.Build options start with the "--" prefix. They are described in the following table.
Table 2. Command line options

Option
Description
--version
Prints information on Boost.Build and Boost.Jam versions.
--help
Access to the online help system. This prints general information on how to use the help system with additional --help* options.
--clean
Removes everything instead of building. Unlike clean target in make, it is possible to clean only some targets.
--debug
Enables internal checks.
--dump-projects
Cause the project structure to be output.
--no-error-backtrace
Don't print backtrace on errors. Primary useful for testing.
--ignore-config
Do not load site-config.jam and user-config.jam

Writing Jamfiles
Writing Jamfiles
This section describes specific information about writing Jamfiles.
Generated headers
Generated headers
Usually, Boost.Build handles implicit dependendies completely automatically. For example, for C++ files, all #include statements are found and handled. The only aspect where user help might be needed is implicit dependency on generated files.
By default, Boost.Build handles such dependencies within one main target. For example, assume that main target "app" has two sources, "app.cpp" and "parser.y". The latter source is converted into "parser.c" and "parser.h". Then, if "app.cpp" includes "parser.h", Boost.Build will detect this dependency. Moreover, since "parser.h" will be generated into a build directory, the path to that directory will automatically added to include path.
Making this mechanism work across main target boundaries is possible, but imposes certain overhead. For that reason, if there's implicit dependency on files from other main targets, the <implicit-dependency> [ link ] feature must be used, for example:
lib parser : parser.y ; exe app : app.cpp : <implicit-dependency>parser ;
The above example tells the build system that when scanning all sources of "app" for implicit-dependencies, it should consider targets from "parser" as potential dependencies.
Build process
Build process
The general overview of the build process was given in the user documentation. This section provides additional details, and some specific rules.
To recap, building a target with specific properties includes the following steps: 1.applying default build,2.selecting the main target alternative to use, 3.determining "common" properties 4.building targets referred by the sources list and dependency properties 5.adding the usage requirements produces when building dependencies to the "common" properties 6.building the target using generators 7.computing the usage requirements to be returned
Alternative selection
Alternative selection
When there are several alternatives, one of them must be selected. The process is as follows:
1.
For each alternative condition is defined as the set of base properies in requirements. [Note: it might be better to specify the condition explicitly, as in conditional requirements].
2.
An alternative is viable only if all properties in condition are present in build request.
3.
If there's one viable alternative, it's choosen. Otherwise, an attempt is made to find one best alternative. An alternative a is better than another alternative b, iff set of properties in b's condition is strict subset of the set of properities of 'a's condition. If there's one viable alternative, which is better than all other, it's selected. Otherwise, an error is reported.
Determining common properties
Determining common properties
The "common" properties is a somewhat artificial term. Those are the intermediate property set from which both the build request for dependencies and properties for building the target are derived.
Since default build and alternatives are already handled, we have only two inputs: build requests and requirements. Here are the rules about common properties.
1.
Non-free feature can have only one value
2.
A non-conditional property in requirement in always present in common properties.
3.
A property in build request is present in common properties, unless (2) tells otherwise.
4.
If either build request, or requirements (non-conditional or conditional) include an expandable property (either composite, or property with specified subfeature value), the behaviour is equivalent to explicitly adding all expanded properties to build request or requirements.
5.
If requirements include a conditional property, and condiiton of this property is true in context of common properties, then the conditional property should be in common properties as well.
6.
If no value for a feature is given by other rules here, it has default value in common properties.
Those rules are declarative, they don't specify how to compute the common properties. However, they provide enough information for the user. The important point is the handling of conditional requirements. The condition can be satisfied either by property in build request, by non-conditional requirements, or even by another conditional property. For example, the following example works as expected: exe a : a.cpp : <toolset>gcc:<variant>release <variant>release:<define>FOO ;
Features and properties
Features and properties
A feature is a normalized (toolset-independent) aspect of a build configuration, such as whether inlining is enabled. Feature names may not contain the '>' character.
Each feature in a build configuration has one or more associated values. Feature values for non-free features may not contain the '<', ':', or '=' characters. Feature values for free features may not contain the '<' character.
A property is a (feature,value) pair, expressed as <feature>value.
A subfeature is a feature which only exists in the presence of its parent feature, and whose identity can be derived (in the context of its parent) from its value. A subfeature's parent can never be another subfeature. Thus, features and their subfeatures form a two-level hierarchy.
A value-string for a feature F is a string of the form value-subvalue1-subvalue2...-subvalueN, where value is a legal value for F and subvalue1...subvalueN are legal values of some of F's subfeatures. For example, the properties <toolset>gcc <toolset-version>3.0.1 can be expressed more conscisely using a value-string, as <toolset>gcc-3.0.1.
A property set is a set of properties (i.e. a collection without duplicates), for instance: <toolset>gcc <runtime-link>static.
A property path is a property set whose elements have been joined into a single string separated by slashes. A property path representation of the previous example would be <toolset>gcc/<runtime-link>static.
A build specification is a property set which fully describes the set of features used to build a target.
Property Validity
For free features, all values are valid. For all other features, the valid values are explicitly specified, and the build system will report an error for the use of an invalid feature-value. Subproperty validity may be restricted so that certain values are valid only in the presence of certain other subproperties. For example, it is possible to specify that the <gcc-target>mingw property is only valid in the presence of <gcc-version>2.95.2.
Feature Attributes
Each feature has a collection of zero or more of the following attributes. Feature attributes are low-level descriptions of how the build system should interpret a feature's values when they appear in a build request. We also refer to the attributes of properties, so that an incidental property, for example, is one whose feature has the incidental attribute.
•
incidental
Incidental features are assumed not to affect build products at all. As a consequence, the build system may use the same file for targets whose build specification differs only in incidental features. A feature which controls a compiler's warning level is one example of a likely incidental feature.
Non-incidental features are assumed to affect build products, so the files for targets whose build specification differs in non-incidental features are placed in different directories as described in "target paths" below. [ where? ]
•
propagated
Features of this kind are propagated to dependencies. That is, if a main target is built using a propagated property, the build systems attempts to use the same property when building any of its dependencies as part of that main target. For instance, when an optimized exectuable is requested, one usually wants it to be linked with optimized libraries. Thus, the <optimization> feature is propagated.
•
free
Most features have a finite set of allowed values, and can only take on a single value from that set in a given build specification. Free features, on the other hand, can have several values at a time and each value can be an arbitrary string. For example, it is possible to have several preprocessor symbols defined simultaneously:
<define>NDEBUG=1 <define>HAS_CONFIG_H=1
•
optional
An optional feature is a feature which is not required to appear in a build specification. Every non-optional non-free feature has a default value which is used when a value for the feature is not otherwise specified, either in a target's requirements or in the user's build request. [A feature's default value is given by the first value listed in the feature's declaration. -- move this elsewhere - dwa]
•
symmetric
A symmetric feature's default value is not automatically included in build variants. Normally a feature only generates a subvariant directory when its value differs from the value specified by the build variant, leading to an assymmetric subvariant directory structure for certain values of the feature. A symmetric feature, when relevant to the toolset, always generates a corresponding subvariant directory.
•
path
The value of a path feature specifies a path. The path is treated as relative to the directory of Jamfile where path feature is used and is translated appropriately by the build system when the build is invoked from a different directory
•
implicit
Values of implicit features alone identify the feature. For example, a user is not required to write "<toolset>gcc", but can simply write "gcc". Implicit feature names also don't appear in variant paths, although the values do. Thus: bin/gcc/... as opposed to bin/toolset-gcc/.... There should typically be only a few such features, to avoid possible name clashes.
•
composite
Composite features actually correspond to groups of properties. For example, a build variant is a composite feature. When generating targets from a set of build properties, composite features are recursively expanded and added to the build property set, so rules can find them if neccessary. Non-composite non-free features override components of composite features in a build property set.
•
dependency
The value of dependency feature if a target reference. When used for building of a main target, the value of dependency feature is treated as additional dependency.
For example, dependency features allow to state that library A depends on library B. As the result, whenever an application will link to A, it will also link to B. Specifying B as dependency of A is different from adding B to the sources of A.
Features which are neither free nor incidental are called base features.
Feature Declaration
The low-level feature declaration interface is the feature rule from the feature module:

rule feature ( name : allowed-values * : attributes * )

A feature's allowed-values may be extended with the feature.extend rule.
Build Variants
Build Variants
A build variant, or (simply variant) is a special kind of composite feature which automatically incorporates the default values of features that . Typically you'll want at least two separate variants: one for debugging, and one for your release code. [ Volodya says: "Yea, we'd need to mention that it's a composite feature and describe how they are declared, in pacticular that default values of non-optional features are incorporated into build variant automagically. Also, do we wan't some variant inheritance/extension/templates. I don't remember how it works in V1, so can't document this for V2.". Will clean up soon -DWA ]
Property refinement
Property refinement
When a target with certain properties is requested, and that target requires some set of properties, it is needed to find the set of properties to use for building. This process is called property refinement and is performed by these rules
1.
If original properties and required properties are not link-compatible, refinement fails.
2.
Each property in the required set is added to the original property set
3.
If the original property set includes property with a different value of non free feature, that property is removed.
Conditional properties
Conditional properties
Sometime it's desirable to apply certain requirements only for a specific combination of other properties. For example, one of compilers that you use issues a pointless warning that you want to suppress by passing a command line option to it. You would not want to pass that option to other compilers. Conditional properties allow you to do just that. Their syntax is:
property ( "," property ) * ":" property
For example, the problem above would be solved by:

exe hello : hello.cpp : <toolset>yfc:<cxxflags>-disable-pointless-warning ;
Target identifiers and references
Target identifiers and references
Target identifier
is used to denote a target. The syntax is:
target-id -> (project-id | target-name | file-name ) | (project-id | directory-name) "//" target-name project-id -> path target-name -> path file-name -> path directory-name -> path
This grammar allows some elements to be recognized as either

•
project id (at this point, all project ids start with slash).
•
name of target declared in current Jamfile (note that target names may include slash).
•
a regular file, denoted by absolute name or name relative to project's sources location.

To determine the real meaning a check is made if project-id by the specified name exists, and then if main target of that name exists. For example, valid target ids might be:

a -- target in current project lib/b.cpp -- regular file /boost/thread -- project "/boost/thread" /home/ghost/build/lr_library//parser -- target in specific project
Rationale:
Target is separated from project by special separator (not just slash), because:
•
It emphasises that projects and targets are different things.
•
It allows to have main target names with slashes.

Target reference
is used to specify a source target, and may additionally specify desired properties for that target. It has this syntax:
target-reference -> target-id [ "/" requested-properties ] requested-properties -> property-path
For example,

exe compiler : compiler.cpp libs/cmdline/<optimization>space ;

would cause the version of cmdline library, optimized for space, to be linked in even if the compiler executable is build with optimization for speed.
Generators
Generators
Warning
The information is this section is likely to be outdated and misleading.
To construct a main target with given properties from sources, it is required to create a dependency graph for that main target, which will also include actions to be run. The algorithm for creating the dependency graph is described here.
The fundamental concept is generator. If encapsulates the notion of build tool and is capable to converting a set of input targets into a set of output targets, with some properties. Generator matches a build tool as closely as possible: it works only when the tool can work with requested properties (for example, msvc compiler can't work when requested toolset is gcc), and should produce exactly the same targets as the tool (for example, if Borland's linker produces additional files with debug information, generator should also).
Given a set of generators, the fundamental operation is to construct a target of a given type, with given properties, from a set of targets. That operation is performed by rule generators.construct and the used algorithm is described below.
Selecting and ranking viable generators
Selecting and ranking viable generators
Each generator, in addition to target types that it can produce, have attribute that affects its applicability in particular sitiation. Those attributes are:
1.
Required properties, which are properties absolutely necessary for the generator to work. For example, generator encapsulating the gcc compiler would have <toolset>gcc as required property.
2.
Optional properties, which increase the generators suitability for a particual build.
Generator's required and optional properties may not include either free or incidental properties. (Allowing this would greatly complicate caching targets).
When trying to construct a target, the first step is to select all possible generators for the requested target type, which required properties are a subset of requested properties. Generators which were already selected up the call stack are excluded. In addition, if any composing generators were selected up the call stack, all other composing generators are ignored (TODO: define composing generators). The found generators are assigned a rank, which is the number of optional properties present in requested properties. Finally, generators with highest rank are selected for futher processing.
Running generators
Running generators
When generators are selected, each is run to produce a list of created targets. This list might include targets which are not of requested types, because generators create the same targets as some tool, and tool's behaviour is fixed. (Note: should specify that in some cases we actually want extra targets). If generator fails, it returns an empty list. Generator is free to call 'construct' again, to convert sources to the types it can handle. It also can pass modified properties to 'construct'. However, a generator is not allowed to modify any propagated properties, otherwise when actually consuming properties we might discover that the set of propagated properties is different from what was used for building sources.
For all targets which are not of requested types, we try to convert them to requested type, using a second call to construct. This is done in order to support transformation sequences where single source file expands to several later. See this message for details.
Selecting dependency graph
Selecting dependency graph
After all generators are run, it is necessary to decide which of successfull invocation will be taken as final result. At the moment, this is not done. Instead, it is checked whether all successfull generator invocation returned the same target list. Error is issued otherwise.
Property adjustment
Property adjustment
Because target location is determined by the build system, it is sometimes necessary to adjust properties, in order to not break actions. For example, if there's an action which generates a header, say "a_parser.h", and a source file "a.cpp" which includes that file, we must make everything work as if a_parser.h is generated in the same directory where it would be generated without any subvariants.
Correct property adjustment can be done only after all targets are created, so the approach taken is:
1.
When dependency graph is constructed, each action can be assigned a rule for property adjustment.
2.
When virtual target is actualized, that rule is run and return the final set of properties. At this stage it can use information of all created virtual targets.
In case of quoted includes, no adjustment can give 100% correct results. If target dirs are not changed by build system, quoted includes are searched in "." and then in include path, while angle includes are searched only in include path. When target dirs are changed, we'd want to make quoted includes to be search in "." then in additional dirs and then in the include path and make angle includes be searched in include path, probably with additional paths added at some position. Unless, include path already has "." as the first element, this is not possible. So, either generated headers should not be included with quotes, or first element of include path should be ".", which essentially erases the difference between quoted and angle includes. Note: the only way to get "." as include path into compiler command line is via verbatim compiler option. In all other case, Boost.Build will convert "." into directory where it occurs.
Transformations cache
Transformations cache
Under certain conditions, an attempt is made to cache results of transformation search. First, the sources are replaced with targets with special name and the found target list is stored. Later, when properties, requested type, and source type are the same, the store target list is retrieved and cloned, with appropriate change in names.

Frequently Asked Questions

Frequently Asked Questions

Frequently Asked Questions
I'm getting "Duplicate name of actual target" error. What does it mean?
I'm getting "Duplicate name of actual target" error. What does it mean?
The most likely case is that you're trying to compile the same file twice, with almost the same, but differing properties. For example:

exe a : a.cpp : <include>/usr/local/include ; exe b : a.cpp ;
The above snippet requires two different compilations of 'a.cpp', which differ only in 'include' property. Since the 'include' property is free, Boost.Build can't generate two objects files into different directories. On the other hand, it's dangerous to compile the file only once -- maybe you really want to compile with different includes.
To solve this issue, you need to decide if file should be compiled once or twice.
1.
Two compile file only once, make sure that properties are the same:

exe a : a.cpp : <include>/usr/local/include ; exe b : a.cpp : <include>/usr/local/include ;
2.
If changing the properties is not desirable, for example if 'a' and 'b' target have other sources which need specific properties, separate 'a.cpp' into it's own target:

obj a_obj : a.cpp : <include>/usr/local/include ; exe a : a_obj ;
3.
To compile file twice, you can make the object file local to the main target:

exe a : [ obj a_obj : a.cpp ] : <include>/usr/local/include ; exe b : [ obj a_obj : a.cpp ] ;
A good question is why Boost.Build can't use some of the above approaches automatically. The problem is that such magic would require additional implementation complexities and would only help in half of the cases, while in other half we'd be silently doing the wrong thing. It's simpler and safe to ask user to clarify his intention in such cases.
Accessing environment variables
Accessing environment variables
Many users would like to use environment variables in Jamfiles, for example, to control location of external libraries. In many cases you better declare those external libraries in the site-config.jam file, as documented in the recipes section. However, if the users already have the environment variables set up, it's not convenient to ask them to set up site-config.jam files as well, and using environment variables might be reasonable.
In Boost.Build V2, each Jamfile is a separate namespace, and the variables defined in environment is imported into the global namespace. Therefore, to access environment variable from Jamfile, you'd need the following code: import modules ; local SOME_LIBRARY_PATH = [ modules.peek : SOME_LIBRARY_PATH ] ; exe a : a.cpp : <include>$(SOME_LIBRARY_PATH) ;
How to control properties order?
How to control properties order?
For internal reasons, Boost.Build sorts all the properties alphabetically. This means that if you write: exe a : a.cpp : <include>b <include>a ; then the command line with first mention the "a" include directory, and then "b", even though they are specified in the opposite order. In most cases, the user doesn't care. But sometimes the order of includes, or other properties, is important. For example, if one uses both the C++ Boost library and the "boost-sandbox" (libraries in development), then include path for boost-sandbox must come first, because some headers may override ones in C++ Boost. For such cases, a special syntax is provided: exe a : a.cpp : <include>a&&b ;
The && symbols separate values of an property, and specify that the order of the values should be preserved. You are advised to use this feature only when the order of properties really matters, and not as a convenient shortcut. Using it everywhere might negatively affect performance.
How to control the library order on Unix?
How to control the library order on Unix?
On the Unix-like operating systems, the order in which static libraries are specified when invoking the linker is important, because by default, the linker uses one pass though the libraries list. Passing the libraries in the incorrect order will lead to a link error. Further, this behaviour is often used to make one library override symbols from another. So, sometimes it's necessary to force specific order of libraries.
Boost.Build tries to automatically compute the right order. The primary rule is that if library a "uses" library b, then library a will appear on the command line before library b. Library a is considered to use b is b is present either in the sources of a or in its requirements. To explicitly specify the use relationship one can use the <use> feature. For example, both of the following lines will cause a to appear before b on the command line: lib a : a.cpp b ; lib a : a.cpp : <use>b ;
The same approach works for searched libraries, too: lib z ; lib png : : <use>z ; exe viewer : viewer png z ;
Can I get output of external program as a variable in a Jamfile?
Can I get output of external program as a variable in a Jamfile?
From time to time users ask how to run an external program and save the result in Jamfile variable, something like: local gtk_includes = [ RUN_COMMAND gtk-config ] ; Unfortunately, this is not possible at the moment. However, if the result of command invocation is to be used in a command to some tool, and you're working on Unix, the following workaround is possible. alias gtk+-2.0 : : : : <cflags>"`pkg-config --cflags gtk+-2.0`" <inkflags>"`pkg-config --libs gtk+-2.0`" ; If you use the "gtk+-2.0" target in sources, then the properties specified above will be added to the build properties and eventually will appear in the command line. Unix command line shell processes the backticks quoting by running the tool and using its output -- which is what's desired in that case. Thanks to Daniel James for sharing this approach.
How to get the project-root location?
How to get the project-root location?
You might want to use the location of the project-root in your Jamfiles. To do it, you'd need to declare path constant in your project-root.jam: path-constant TOP : . ; After that, the TOP variable can be used in every Jamfile.
How to change compilation flags for one file?
How to change compilation flags for one file?
If one file must be compiled with special options, you need to explicitly declare an obj target for that file and then use that target in your exe or lib target: exe a : a.cpp b ; obj b : b.cpp : <optimization>off ; Of course you can use other properties, for example to specify specific compiler options: exe a : a.cpp b ; obj b : b.cpp : <cflags>-g ; You can also use conditional properties for finer control: exe a : a.cpp b ; obj b : b.cpp : <variant>release:<optimization>off ;
Why are the dll-path and hardcode-dll-paths properties useful?
Why are the dll-path and hardcode-dll-paths properties useful?
(This entry is specific to Unix system.)Before answering the questions, let's recall a few points about shared libraries. Shared libraries can be used by several applications, or other libraries, without phisycally including the library in the application. This can greatly decrease the total size of applications. It's also possible to upgrade a shared library when the application is already installed. Finally, shared linking can be faster.
However, the shared library must be found when the application is started. The dynamic linker will search in a system-defined list of paths, load the library and resolve the symbols. Which means that you should either change the system-defined list, given by the LD_LIBRARY_PATH environment variable, or install the libraries to a system location. This can be inconvenient when developing, since the libraries are not yet ready to be installed, and cluttering system paths is undesirable. Luckily, on Unix there's another way.
An executable can include a list of additional library paths, which will be searched before system paths. This is excellent for development, because the build system knows the paths to all libraries and can include them in executables. That's done when the hardcode-dll-paths feature has the true value, which is the default. When the executables should be installed, the story is different.
Obviously, installed executable should not hardcode paths to your development tree. (The stage rule explicitly disables the hardcode-dll-paths feature for that reason.) However, you can use the dll-path feature to add explicit paths manually. For example: stage installed : application : <dll-path>/usr/lib/snake <location>/usr/bin ; will allow the application to find libraries placed to /usr/lib/snake.
If you install libraries to a nonstandard location and add an explicit path, you get more control over libraries which will be used. A library of the same name in a system location will not be inadvertently used. If you install libraries to a system location and do not add any paths, the system administrator will have more control. Each library can be individually upgraded, and all applications will use the new library.
Which approach is best depends on your situation. If the libraries are relatively standalone and can be used by third party applications, they should be installed in the system location. If you have lots of libraries which can be used only by our application, it makes sense to install it to a nonstandard directory and add an explicit path, like the example above shows. Please also note that guidelines for different systems differ in this respect. The Debian guidelines prohibit any additional search paths, and Solaris guidelines suggest that they should always be used.
Targets in site-config.jam
Targets in site-config.jam
It is desirable to declare standard libraries available on a given system. Putting target declaration in Jamfile is not really good, since locations of the libraries can vary. The solution is to put the following to site-config.jam.
import project ; project.initialize $(__name__) ; project site-config ; lib zlib : : <name>z ;
The second line allows this module to act as project. The third line gives id to this project — it really has no location and cannot be used otherwise. The fourth line just declares a target. Now, one can write: exe hello : hello.cpp /site-config//zlib ; in any Jamfile.

Boost.Build v2 architecture

Boost.Build v2 architecture

Appendix B. Boost.Build v2 architecture
This document is work-in progress. Don't expect much from it yet.
Overview
Overview
The Boost.Build code is structured in four different components: "kernel", "util", "build" and "tools". The first two are relatively uninteresting, so we'll focus on the remaining pair. The "build" component provides classes necessary to declare targets, determine which properties should be used for their building, and for creating the dependency graph. The "tools" component provides user-visible functionality. It mostly allows to declare specific kind of main targets, and declare avaiable tools, which are then used when creating the dependency graph.
The build layer
The build layer
The build layer has just four main parts -- abstract targets, virtual targets, generators and properties. The abstract targets, represented by the "abstract-target" class, correspond to main targets -- which, as you recall, can produce different files depending on properties. Virtual targets, represented by the 'virtual-target' class correspond to real files. The abstract-target class has a method 'generate', which is given a set of properties and produces virtual targets for those properties.
There are several classes derived from "abstract-target". The "main-target" class represents top-level main target, the "project-target" acts like container for all main targets, and "basic-target" class is a base class for all further target types.
Since each main target can have several alternatives, all top-level target objects are just containers, referring to "real" main target classes. The type is that container is "main-target". For example, given: alias a ; lib a : a.cpp : <toolset>gcc ; we would have one-top level instance of "main-target-class", which will contain one instance of "alias-target-class" and one instance of "lib-target-class". The "generate" method of "main-target" decides which of the alternative should be used, and call "generate" on the corresponding instance.
Each alternative is a instance of a class derived from "basic-target". The "basic-target.generate" does several things that are always should be done: •Determines what properties should be used for building the target. This includes looking at requested properties, requirements, and usage requirements of all sources.•Builds all sources•Computes the usage requirements which should be passes back. For the real work of constructing virtual target, a new method "construct" is called.
The "construct" method can be implemented in any way by classes derived from "basic-target", but one specific derived class plays the central role -- "typed-target". That class holds the desired type of file to be produces, and calls the generators modules to do the job.
Generators are Boost.Build abstractions for a tool. For example, one can register a generator which converts target of type CPP into target of type OBJ. When run with on a virtual target with CPP type, the generator will construct the virtual target of type OBJ. The "generators" module implements an algorithm, which given a list of sources, the desired type and a list of properties, find all the generators which can perform the conversion.
The virtual targets which are produces by the main targets form a graph. Targets which are produces from other ones refer to an instance of "action" class, which in turn refers to action's sources, which can further refer to actions. The sources, which are not produces from anything, don't refer to any actions.
When all virtual targets are produced, they are "actualized". This means that the real file names are computed, and the commands that should be run are generated. This is done by "virtual-target.actualize" and "action.actualize" methods. The first is conceptually simple, while the second need additional explanation. The commands in bjam are generated in two-stage process. First, a rule with the appropriate name (for example "gcc.compile") is called and is given the names of targets. The rule sets some variables, like "OPTIONS". After that, the command string is taken, and variable are substitutes, so use of OPTIONS inside the command string become the real compile options.
Boost.Build added a third stage to simplify things. It's now possible to automatically convert properties to appropriate assignments to variables. For example, <debug-symbols>on would add "-g" to the OPTIONS variable, without requiring to manually add this logic to gcc.compile. This functionality is part of the "toolset" module.
When target paths are computed and the commands are set, Boost.Build just gives control to bjam, which controls the execution of commands.
The tools layer
The tools layer
Write me!
Targets
Targets
NOTE: THIS SECTION IS NOT EXPECTED TO BE READ! There are two user-visible kinds of targets in Boost.Build. First are "abstract" — they correspond to things declared by user, for example, projects and executable files. The primary thing about abstract target is that it's possible to request them to be build with a particular values of some properties. Each combination of properties may possible yield different set of real file, so abstract target do not have a direct correspondence with files.
File targets, on the contary, are associated with concrete files. Dependency graphs for abstract targets with specific properties are constructed from file targets. User has no was to create file targets, however it can specify rules that detect file type for sources, and also rules for transforming between file targets of different types. That information is used in constructing dependency graph, as desribed in the "next section". [ link? ] Note:File targets are not the same as targets in Jam sense; the latter are created from file targets at the latest possible moment. Note:"File target" is a proposed name for what we call virtual targets. It it more understandable by users, but has one problem: virtual targets can potentially be "phony", and not correspond to any file.
Dependency scanning
Dependency scanning
Dependency scanning is the process of finding implicit dependencies, like "#include" statements in C++. The requirements for right dependency scanning mechanism are:
•
Support for different scanning algorithms. C++ and XML have quite different syntax for includes and rules for looking up included files.
•
Ability to scan the same file several times. For example, single C++ file can be compiled with different include paths.
•
Proper detection of dependencies on generated files.
•
Proper detection of dependencies from generated file.
Support for different scanning algorithms
Different scanning algorithm are encapsulated by objects called "scanners". Please see the documentation for "scanner" module for more details.
Ability to scan the same file several times
As said above, it's possible to compile a C++ file twice, with different include paths. Therefore, include dependencies for those compilations can be different. The problem is that bjam does not allow several scans of the same target.
The solution in Boost.Build is straigtforward. When a virtual target is converted to bjam target (via virtual-target.actualize method), we specify the scanner object to be used. The actualize method will create different bjam targets for different scanners.
All targets with specific scanner are made dependent on target without scanner, which target is always created. This is done in case the target is updated. The updating action will be associated with target without scanner, but if sources for that action are touched, all targets — with scanner and without should be considered outdated.
For example, assume that "a.cpp" is compiled by two compilers with different include path. It's also copied into some install location. In turn, it's produced from "a.verbatim". The dependency graph will look like:
a.o (<toolset>gcc) <--(compile)-- a.cpp (scanner1) ----+ a.o (<toolset>msvc) <--(compile)-- a.cpp (scanner2) ----| a.cpp (installed copy) <--(copy) ----------------------- a.cpp (no scanner) ^ | a.verbose --------------------------------+
Proper detection of dependencies on generated files.
This requirement breaks down to the following ones.
1.
If when compiling "a.cpp" there's include of "a.h", the "dir" directory is in include path, and a target called "a.h" will be generated to "dir", then bjam should discover the include, and create "a.h" before compiling "a.cpp".
2.
Since almost always Boost.Build generates targets to a "bin" directory, it should be supported as well. I.e. in the scanario above, Jamfile in "dir" might create a main target, which generates "a.h". The file will be generated to "dir/bin" directory, but we still have to recornize the dependency.
The first requirement means that when determining what "a.h" means, when found in "a.cpp", we have to iterate over all directories in include paths, checking for each one:
1.
If there's file "a.h" in that directory, or
2.
If there's a target called "a.h", which will be generated to that directory.
Classic Jam has built-in facilities for point (1) above, but that's not enough. It's hard to implement the right semantic without builtin support. For example, we could try to check if there's targer called "a.h" somewhere in dependency graph, and add a dependency to it. The problem is that without search in include path, the semantic may be incorrect. For example, one can have an action which generated some "dummy" header, for system which don't have the native one. Naturally, we don't want to depend on that generated header on platforms where native one is included.
There are two design choices for builtin support. Suppose we have files a.cpp and b.cpp, and each one includes header.h, generated by some action. Dependency graph created by classic jam would look like:
a.cpp -----> <scanner1>header.h [search path: d1, d2, d3]

<d2>header.h --------> header.y [generated in d2]

b.cpp -----> <scanner2>header.h [ search path: d1, d2, d4]
In this case, Jam thinks all header.h target are not realated. The right dependency graph might be:

a.cpp ---- \ \ >----> <d2>header.h --------> header.y / [generated in d2] / b.cpp ----

or

a.cpp -----> <scanner1>header.h [search path: d1, d2, d3] | (includes) V <d2>header.h --------> header.y [generated in d2] ^ (includes) | b.cpp -----> <scanner2>header.h [ search path: d1, d2, d4]
The first alternative was used for some time. The problem however is: what include paths should be used when scanning header.h? The second alternative was suggested by Matt Armstrong. It has similiar effect: add targets which depend on <scanner1>header.h will also depend on <d2>header.h. But now we have two different target with two different scanners, and those targets can be scanned independently. The problem of first alternative is avoided, so the second alternative is implemented now.
The second sub-requirements is that targets generated to "bin" directory are handled as well. Boost.Build implements semi-automatic approach. When compiling C++ files the process is:
1.
The main target to which compiled file belongs is found.
2.
All other main targets that the found one depends on are found. Those include main target which are used as sources, or present as values of "dependency" features.
3.
All directories where files belonging to those main target will be generated are added to the include path.
After this is done, dependencies are found by the approach explained previously.
Note that if a target uses generated headers from other main target, that main target should be explicitly specified as dependency property. It would be better to lift this requirement, but it seems not very problematic in practice.
For target types other than C++, adding of include paths must be implemented anew.
Proper detection of dependencies from generated files
Suppose file "a.cpp" includes "a.h" and both are generated by some action. Note that classic jam has two stages. In first stage dependency graph graph is build and actions which should be run are determined. In second stage the actions are executed. Initially, neither file exists, so the include is not found. As the result, jam might attempt to compile a.cpp before creating a.h, and compilation will fail.
The solution in Boost.Jam is to perform additional dependency scans after targets are updated. This break separation between build stages in jam — which some people consider a good thing — but I'm not aware of any better solution.
In order to understand the rest of this section, you better read some details about jam dependency scanning, available at this link.
Whenever a target is updated, Boost.Jam rescans it for includes. Consider this graph, created before any actions are run.
A -------> C ----> C.pro / B --/ C-includes ---> D
Both A and B have dependency on C and C-includes (the latter dependency is not shown). Say during building we've tried to create A, then tried to create C and successfully created C.
In that case, the set of includes in C might well have changed. We do not bother to detect precisely which includes were added or removed. Instead we create another internal node C-includes-2. Then we determine what actions should be run to update the target. In fact this mean that we perform logic of first stage while already executing stage.
After actions for C-includes-2 are determined, we add C-includes-2 to the list of A's dependents, and stage 2 proceeds as usual. Unfortunately, we can't do the same with target B, since when it's not visited, C target does not know B depends on it. So, we add a flag to C which tells and it was rescanned. When visiting B target, the flag is notices and C-includes-2 will be added to the list of B's dependencies.
Note also that internal nodes are sometimes updated too. Consider this dependency graph:
a.o ---> a.cpp a.cpp-includes --> a.h (scanned) a.h-includes ------> a.h (generated) | | a.pro <-------------------------------------------+
Here, out handling of generated headers come into play. Say that a.h exists but is out of date with respect to "a.pro", then "a.h (generated)" and "a.h-includes" will be marking for updating, but "a.h (scanned)" won't be marked. We have to rescan "a.h" file after it's created, but since "a.h (generated)" has no scanner associated with it, it's only possible to rescan "a.h" after "a.h-includes" target was updated.
Tbe above consideration lead to decision that we'll rescan a target whenever it's updated, no matter if this target is internal or not.
Warning
The remainder of this document is not indended to be read at all. This will be rearranged in future.
File targets
As described above, file targets corresponds to files that Boost.Build manages. User's may be concerned about file targets in three ways: when declaring file target types, when declaring transformations between types, and when determining where file target will be placed. File targets can also be connected with actions, that determine how the target is created. Both file targets and actions are implemented in the virtual-target module.
Types
A file target can be given a file, which determines what transformations can be applied to the file. The type.register rule declares new types. File type can also be assigned a scanner, which is used to find implicit dependencies. See "dependency scanning" [ link? ] below.
Target paths
To distinguish targets build with different properties, they are put in different directories. Rules for determining target paths are given below:
1.
All targets are placed under directory corresponding to the project where they are defined.
2.
Each non free, non incidental property cause an additional element to be added to the target path. That element has the form <feature-name>-<feature-value> for ordinary features and <feature-value> for implicit ones. [Note about composite features].
3.
If the set of free, non incidental properties is different from the set of free, non incidental properties for the project in which the main target that uses the target is defined, a part of the form main_target-<name> is added to the target path. Note:It would be nice to completely track free features also, but this appears to be complex and not extremely needed.
For example, we might have these paths:
debug/optimization-off debug/main-target-a