diff --git a/doc/html/Assignable.html b/doc/html/Assignable.html deleted file mode 100644 index c6cb3991ad..0000000000 --- a/doc/html/Assignable.html +++ /dev/null @@ -1,101 +0,0 @@ - -
- -![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Assignable
-Assignable types must have copy constructors,
- operator=
for assignment, and the swap()
- function defined.
x
, y
-- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
once_flag
instances to indicate that the
- logically associated routine has not been run yet. See
- call_once for more details.- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_TRIBOOL_THIRD_STATE — Declare a new name for the third state of a tribool.
-BOOST_TRIBOOL_THIRD_STATE(Name)
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 }
-- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_VARIANT_ENUM_PARAMS —
Enumerate parameters for use with
- variant
.
BOOST_VARIANT_ENUM_PARAMS(param)
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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_VARIANT_LIMIT_TYPES —
Expands to the length of the
- template parameter list for
- variant
.
BOOST_VARIANT_LIMIT_TYPES
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BidirectionalIterator
-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).
-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
-i
, j
-x
category must be - derived from std::bidirectional_iterator_tag. -
Name | -Expression | -Type | -Precondition | -Semantics | -Postcondition | -
---|---|---|---|---|---|
Predecrement |
---i |
-Iter & |
-
|
-- | - |
Postdecrement |
-i-- |
-Iter |
-Same as for predecrement |
-Equivalent to |
-
|
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
CopyConstructible
-Copy constructible types must be able to be constructed from another - member of the type.
-x
, y
-- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
DefaultConstructible
-- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
EqualityComparable
-x
, y
-- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::FinderConcept — Finder concept.
-template<typename FinderT, typename IteratorT> -struct FinderConcept { - - // public member functions - void constraints() ; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::FormatterConcept — Formatter concept.
-template<typename FormatterT, typename FinderT, typename IteratorT> -struct FormatterConcept { - - // public member functions - void constraints() ; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
ForwardIterator
-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).
-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
-i
, j
-x
Name | -Expression | -Type | -Precondition | -Semantics | -Postcondition | -
---|---|---|---|---|---|
Dereference |
-*i |
-const-if-not-mutable value_type & |
-
|
-- | - |
Member access |
-i->{member-name} (return type is pointer-to-object type) |
-const-if-not-mutable value_type * |
-
|
-- | - |
Preincrement |
-++i |
-Iter & |
-
|
-- | - |
Postincrement |
-i++ |
-Iter |
-
|
-Equivalent to |
-
|
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
InputIterator
-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).
-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
-i
, j
-x
category must be - derived from std::input_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible. -
value_type must be - a model of CopyConstructible. -
difference_type must be - a model of SignedInteger. -
Name | -Expression | -Type | -Precondition | -Semantics | -Postcondition | -
---|---|---|---|---|---|
Dereference |
-*i |
-Convertible to value_type |
-
|
-- | - |
Preincrement |
-++i |
-Iter & |
-
|
-- | - |
Postincrement |
-i++ |
-- |
|
-Equivalent to |
-
|
-
Postincrement and dereference |
-*i++ |
-Convertible to value_type |
-
|
-Equivalent to |
-
|
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
LessThanComparable
-x
, y
-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. |
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
OutputIterator
-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).
-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
-i
, j
-x
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 must be - derived from std::output_iterator_tag, a model of DefaultConstructible, and a model of CopyConstructible. -
difference_type must be - a model of SignedInteger. -
Name | -Expression | -Type | -Precondition | -Semantics | -Postcondition | -
---|---|---|---|---|---|
Dereference |
-*i |
-- |
|
-- | - |
Dereference and assign |
-*i = x |
-- |
|
-- |
|
-
Preincrement |
-++i |
-Iter & |
-
|
-- | - |
Postincrement |
-i++ |
-- |
|
-Equivalent to |
-
|
-
Postincrement, dereference, and assign |
-*i++ = x |
-- |
|
-Equivalent to |
-
|
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
RandomAccessIterator
-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).
-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)
-i
, j
-x
n
int_off
category must be - derived from std::random_access_iterator_tag. -
Name | -Expression | -Type | -Semantics | -
---|---|---|---|
Motion |
-i += n |
-Iter & |
-Equivalent to applying |
-
Motion (with integer offset) |
-i += int_off |
-Iter & |
-Equivalent to applying |
-
Subtractive motion |
-i -= n |
-Iter & |
-Equivalent to |
-
Subtractive motion (with integer offset) |
-i -= int_off |
-Iter & |
-Equivalent to |
-
Addition |
-i + n |
-Iter |
-Equivalent to |
-
Addition with integer |
-i + int_off |
-Iter |
-Equivalent to |
-
Addition (count first) |
-n + i |
-Iter |
-Equivalent to |
-
Addition with integer (count first) |
-int_off + i |
-Iter |
-Equivalent to |
-
Subtraction |
-i - n |
-Iter |
-Equivalent to |
-
Subtraction with integer |
-i - int_off |
-Iter |
-Equivalent to |
-
Distance |
-i - j |
-difference_type |
-The number of times |
-
Element access |
-i[n] |
-const-if-not-mutable value_type & |
-Equivalent to |
-
Element access with integer index |
-i[int_off] |
-const-if-not-mutable value_type & |
-Equivalent to |
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
SignedInteger
-x
, y
, z
-a
, b
-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 |
-
- | Copyright © 2001, 2002 Indiana University Copyright © 2000, 2001 University of Notre Dame du Lac Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew Lumsdaine Copyright © 1996-1999 Silicon Graphics Computer Systems, Inc. Copyright © 1994 Hewlett-Packard Company |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
Implements string->string mapping with convenient value casting facilities.
-abstract_variables_map
construct/copy/destructabstract_variables_map();
abstract_variables_map(const abstract_variables_map * next);
~abstract_variables_map();
abstract_variables_map
public member functionsconst 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.
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 functionsvirtual const variable_value & get(const std::string & name) const;-
Returns value of variable 'name' stored in *this, or empty value otherwise.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::all — 'All' predicate
--template<typename RangeT, typename PredicateT> - bool all(const RangeT & Input, PredicateT Pred);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::all_date_names_put — A date name output facet that takes an array of char* to define strings.
-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; -};
all_date_names_put
construct/copy/destructall_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
protected member functionsvirtual void do_put_month_short(iter_type & oitr, month_enum moy) const;
virtual void do_put_month_long(iter_type & oitr, month_enum moy) const;
virtual void -do_put_special_value(iter_type & oitr, special_value_enum sv) const;
virtual void do_put_weekday_short(iter_type & oitr, weekday_enum wd) const;
virtual void do_put_weekday_long(iter_type & oitr, weekday_enum wd) const;
virtual void do_month_sep_char(iter_type & oitr) const;
virtual void do_day_sep_char(iter_type & oitr) const;
virtual ymd_order_spec do_date_order() const;
virtual month_format_spec do_month_format() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::ambiguous_result — simple exception for reporting when STD or DST cannot be determined
--struct ambiguous_result { - // construct/copy/destruct - ambiguous_result(std::string = ""); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -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.
Last revised: March 15, 2003 at 23:12:35 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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:
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 *); -}-
- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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, constboost::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(constboost::any
& operand) -{ - return operand.type
() == typeid(int); -} - -bool is_char_ptr(constboost::any
& operand) -{ - try - { -any_cast
<const char *>(operand); - return true; - } - catch(constboost::bad_any_cast
&) - { - return false; - } -} - -bool is_string(constboost::any
& operand) -{ - returnany_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;
- ...
-};
-
-- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::any_cast —
Custom keyword cast for extracting a value
- of a given type from an
- any
.
-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);
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.
- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- --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.
-
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::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.
--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);
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:
-
-
variant
operand.variant
- operands.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.)
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::apply_visitor_delayed_t — Adapts a visitor for use as a function object.
-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 &); -};
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
function object interfacetemplate<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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2001-2004 Nicolai M. Josuttis
Table of Contents
- -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:
-
swap
() has no constant complexity.size
() is always constant, based on the second template argument of the type.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.Last revised: January 30, 2004 at 03:51:06 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2004 Nicolai M. Josuttis | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
- | Copyright © 2001-2004 Nicolai M. Josuttis | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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: -
-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.
-- | Copyright © 2001-2004 Nicolai M. Josuttis | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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>&); -}-
- | Copyright © 2001-2004 Nicolai M. Josuttis | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::bad_adjustment — simple exception for UTC daylight savings adjustment
--struct bad_adjustment { - // construct/copy/destruct - bad_adjustment(std::string = ""); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::bad_any_cast — The exception thrown in the event of a failed
- any_cast
of an
- any
value.
-class bad_any_cast : public std::bad_cast { -public: - virtual const char * what() const; -};
- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::bad_day_of_month — Exception type for gregorian day of month (1..31).
--struct bad_day_of_month { - // construct/copy/destruct - bad_day_of_month(); - bad_day_of_month(const std::string &); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::bad_day_of_year — Exception type for day of year (1..366).
--struct bad_day_of_year { - // construct/copy/destruct - bad_day_of_year(); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::bad_field_count —
--struct bad_field_count { - // construct/copy/destruct - bad_field_count(const std::string &); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::bad_function_call — An exception type thrown when an instance of a function
object is empty when invoked.
-class bad_function_call : public std::runtime_error { -public: - // construct/copy/destruct - bad_function_call(); -};
bad_function_call
construct/copy/destructbad_function_call();-
Effects:
-
- Constructs a bad_function_call
exception object.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::bad_get —
The exception thrown in the event of a failed application of
- boost::get
on the given
- operand value.
-class bad_get : public std::exception { -public: - virtual const char * what() const; -};
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::bad_month — Exception thrown if a greg_month is constructed with a value out of range.
--struct bad_month { - // construct/copy/destruct - bad_month(); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::bad_offset — simple exception for UTC and Daylight savings start/end offsets
--struct bad_offset { - // construct/copy/destruct - bad_offset(std::string = ""); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::bad_visit —
The exception thrown in the event of a visitor - unable to handle the visited value.
--class bad_visit : public std::exception { -public: - virtual const char * what() const; -};
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::bad_weekday — Exception that flags that a weekday number is incorrect.
--struct bad_weekday { - // construct/copy/destruct - bad_weekday(); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::bad_year — Exception type for gregorian year.
--struct bad_year { - // construct/copy/destruct - bad_year(); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::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.
--class barrier : private boost::noncopyable // Exposition only -{ -public: - // construct/copy/destruct - barrier(size_t); - ~barrier(); - - // waiting - bool wait(); -};
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/destructbarrier(size_t count);-
Effects:
-
- Constructs a barrier object that
- will cause count
threads to block on a call to wait()
.
-
~barrier();-
Effects:
-
- Destroys *this
. If threads are still executing
- their wait()
operations, the behavior for these threads is undefined.
-
barrier
waitingbool 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.
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.
-- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::base_time — Representation of a precise moment in time, including the date.
-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(special_values); - base_time(const time_rep_type &); - - // public member functions - date_type date() const; - time_duration_type time_of_day() const; - std::string zone_name(bool = false) const; - std::string zone_abbrev(bool = false) const; - std::string zone_as_posix_string() const; - bool is_not_a_date_time() const; - bool is_infinity() const; - bool is_pos_infinity() const; - bool is_neg_infinity() const; - bool is_special() 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 &) ; -};
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
public member functionsdate_type date() const;
time_duration_type time_of_day() const;
std::string zone_name(bool as_offset = false) const;-
Optional bool parameter will return time zone as an offset (ie "+07:00"). Empty string is returned for classes that do not use a time_zone
-std::string zone_abbrev(bool as_offset = false) const;-
Optional bool parameter will return time zone as an offset (ie "+07:00"). Empty string is returned for classes that do not use a time_zone
-std::string zone_as_posix_string() const;
bool is_not_a_date_time() const;
bool is_infinity() const;
bool is_pos_infinity() const;
bool is_neg_infinity() const;
bool is_special() const;
bool operator==(const time_type & rhs) const;
bool operator<(const time_type & rhs) const;
time_duration_type operator-(const time_type & rhs) const;
time_type operator+(const date_duration_type & dd) const;
time_type operator+=(const date_duration_type & dd) ;
time_type operator-(const date_duration_type & dd) const;
time_type operator-=(const date_duration_type & dd) ;
time_type operator+(const time_duration_type & td) const;
time_type operator+=(const time_duration_type & td) ;
time_type operator-(const time_duration_type & rhs) const;
time_type operator-=(const time_duration_type & td) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::basic_command_line_parser —
-template<typename charT> -class basic_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() ; -};
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/destructbasic_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.
-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 functionsbasic_command_line_parser & options(const options_description & desc) ;-
Sets options descriptions to use.
-basic_command_line_parser & -positional(const positional_options_description & desc) ;-
Sets positional options description to use.
-basic_command_line_parser & style(int ) ;-
Sets the command line style.
-basic_command_line_parser & extra_parser(ext_parser ) ;-
Sets the extra parsers.
-basic_parsed_options< charT > run() ;
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; - bool unregistered; -};
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.
- - -- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
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/destructbasic_parsed_options(const options_description * description);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-dll-path
and
- hardcode-dll-paths
properties useful?
- Last revised: December 29, 2004 at 22:17:38 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -This section will provide the information necessary to create your own - projects using Boost.Build. The information provided here is relatively - high-level, and Chapter 26, Detailed reference as - well as the on-line help system must be used to obtain - low-level documentation (see ???).
-Boost.Build actually consists of two parts - Boost.Jam, a - build engine with its own interpreted language, and Boost.Build itself, - implemented in Boost.Jam's language. The chain of events when - you type bjam on the command line is: -
-Boost.Jam tries to find Boost.Build and loads the top-level - module. The exact process is described in the section called “Initialization”
The top-level module loads user-defined configuration
- files, user-config.jam
and site-config.jam
, which define
- available toolsets.
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.
Finally, using the 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 need to know only - three things: -
-Some Basics about the Boost.Jam language. See the - Boost.Jam - and Classic - Jam documentation. -
The Boost.Build configuration is specified in the file
- user-config.jam
. You can edit the one that 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 declare 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 the gcc compiler
- available.
-
- Since nothing but a tool name is specified, Boost.Build will
- pick some default settings. For example, it will use the
- gcc executable found in the
- PATH
, or look in some known installation
- locations. In most cases, this strategy works automatically. In
- case you have several versions of a compiler, it's installed in
- some unusual location, or you need to tweak its configuration,
- you'll need to pass additional parameters to the
- using
rule. The parameters to
- using
can be different for each
- tool. You can obtain specific documentation for any tool's
- configuration parameters by invoking
-
-bjam --help tool-name
.init
-
-
- That said, for all the compiler toolsets Boost.Build supports
- out-of-the-box, the list of parameters to
- using
is the same: toolset-name
, version
, invocation-command
, and options
.
-
The version
- parameter identifies the toolset version, in case you have
- several installed. 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 that must be executed to run the
- compiler. This parameter can usually be omitted if the compiler
- executable
-
has its “usual
- name” and is in the PATH
,
- or
was installed in a standard - “installation directory”, - or
can be found through a global mechanism like the - Windows registry.
- - For example: -
--using msvc : 7.1 ; -using gcc ; --
-If the compiler can be found in the PATH
but only by a
-nonstandard name, you can just supply that name:
-
-using gcc : : g++-3.2 ; --
-Otherwise, it might be necessary to supply the complete path to the -compiler executable: -
--using msvc : : Z:/Programs/Microsoft Visual Studio/vc98/bin/cl ; --
-Some Boost.Build toolsets will use that path to take additional -actions required before invoking the compiler, such as calling -vendor-supplied scripts to set up its required environment variables. -
-To configure several versions of a toolset, simply invoke
- the using
rule multiple times:
-
-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 the
- PATH
will be used, and there's no need to
- explicitly specify the command.
-
As shown above, both the version
and invocation-command
parameters are
- optional, but there's an important restriction: if you configure
- the same toolset more than 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
call does
- not specify a version
.
-
The options
- parameter is used to fine-tune the configuration. All of
- Boost.Build's standard compiler toolsets accept properties of the
- four builtin features cflags
,
- cxxflags
, compileflags
and
- linkflags
as options
specifying flags that will be
- always passed to the corresponding tools. Values of the
- cflags
feature are passed directly to the C
- compiler, values of the cxxflags
feature are
- passed directly to the C++ compiler, and values of the
- compileflags
feature are passed to both. For
- example, to configure a gcc toolset so that it
- always generates 64-bit code you could write:
-
-using gcc : 3.4 : : <compileflags>-m64 <linkflags>-m64 ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 a Jamfile is more like a “metatarget.” - - Depending on the properties 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 built several times with different properties, - - producing different files. -
-- This means that for Boost.Build, you cannot directly obtain a build - variant from a Jamfile. There could be several variants requested by the - user, and each target can be built with different properties. -
-- The command line specifies which targets to build and with which - 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, is - described in the section called “Command line”. -
-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 details are given in the section called “Build process”. -
-Applying default build. If the default-build - property of a target specifies a value of a feature that is not - present in the build request, that value is added.
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. -
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. -
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. -
Adding the usage requirements produced 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. -
Building the target using generators. To convert the - sources to the desired type, Boost.Build uses "generators" --- - objects that correspond to tools like compilers and - linkers. Each generator declares what type of targets it - - 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. -
Computing the usage requirements to be returned. The - conditional properties in usage requirements are expanded - - and the - result is returned.
Often, a user builds a complete project, not just one main - target. In fact, invoking bjam without - arguments - - builds the project defined in the current - directory.
-When a project is built, 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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
variant
- A feature that combines several low-level features, making - it easy to request common build configurations. -
-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 builds to suit the expectations of - people used to various IDEs. - - It's assumed other folks don't - have any specific expectation in this point. -
-link
-- A feature that controls how libraries are built. -
-Allowed values:shared
,
- static
source
<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 X
will
- be included as a source in all of the project's main
- targets.
- library
dependency
#include
paths) of some
- library to be applied, but don't want to link to it.
- use
#include
paths) of some
- library to be applied, but don't want to link to it.
- dll-path
dll-path
and
- hardcode-dll-paths
properties useful?
- ”
- in Chapter 27, Frequently Asked Questions 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 built 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.
- Note that on Mac OSX, the paths are unconditionally hardcoded by
- the linker, and it's not possible to disable that behaviour.
-
cflags
, cxxflags
, linkflags
-cflags
that's both C and C++
- compilers, for cxxflags
that's C++ compiler and for
- linkflags
that's linker. The features are handy when
- you're trying to do something special that cannot be achieved by
- higher-level feature in Boost.Build.
- - | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 that 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. -
-
- 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 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 that should be
- passed to the -l
option, and the file
- property specifies the file location. The search
feature
- specifies paths in which to search for the library. That feature can
- be specified several times, or it 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
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 gui : : <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 ; --
When a library (say, a
), that 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 that link to a
will also link to
- b
.
-
One feature of Boost.Build that is very important for libraries - is usage requirements. - - For example, if you write: -
--lib helpers : helpers.cpp : : : <include>. ; --
- then the compiler include path for all targets that use
- helpers
will contain the directory
-
- where the target is defined.path to "helpers.cpp". The user
- only needs to add helpers
to the list of sources,
- and needn't consider the requirements its use imposes on a
- dependent target. This feature greatly simplifies Jamfiles.
-
If you don't want shared libraries to include all libraries - that 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 that link to a
also link to
- b
. In this case, even for shared linking, the
- a
library won't even refer to b
.
-
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 an 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 threads : /boost/thread//boost_thread : <link>static ; --
- and use only the threads
alias in your Jamfiles.
-
- You can also 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.
-
For installing a built target you should use the
- install
rule, which follows the common syntax. For
- example:
-
-install dist : hello helpers ; --
- will cause the targets hello
and helpers
to
- be moved to the dist
directory, relative to
- Jamfile's directory. The directory can
- be changed with the location
property:
-
-install dist : hello helpers : <location>/usr/bin ; --
- While you can achieve the same effect by changing the target name to
- /usr/bin
, using the location
- property is better, because it allows you to use a memnonic target
- name.
-
The location
property is especially handy when the location
- is not fixed, but depends on build variant or environment variables:
-
-install dist : hello helpers : <variant>release:<location>dist/release - <variant>debug:<location>dist/debug ; -install dist2 : hello helpers : <location>$(DIST) ; --
- See also conditional - properties and environment variables
-
- Specifying the names of all libraries to install can be boring. The
- install
allows you to specify only the top-level executable
- targets to install, and automatically install all dependencies:
-
-install dist : hello - : <install-dependencies>on <install-type>EXE - <install-type>LIB - ; --
- will find all targets that hello
depends on, and install
- all of the which are either executables or libraries. More
- specifically, for each target, other targets that were specified as
- sources or as dependency properties, will be recursively found. One
- exception is that targets referred with the use
feature
- are not considered, because that feature is typically used to refer to
- header-only libraries.
- If the set of target types is specified, only targets of that type
- will be installed, otherwise, all found target will be installed.
-
The alias
- rule can be used when targets must be installed into several
- directories:
-
-install install : install-bin install-lib ; -install install-bin : applications : /usr/bin ; -install install-lib : helper : /usr/lib ; --
Because the install
rule just copies targets, most
- free features [6]
- have no effect when used in requirements of the install
.
- The only two which matter are
- dependency
and, on Unix,
- dll-path
.
-
- (Unix specific). On Unix, executables built with Boost.Build typically
- contain the list of paths to all used dynamic libraries. For
- installing, this is not desired, so Boost.Build relinks the executable
- with an empty list of paths. You can also specify additional paths for
- installed executables with the dll-path
feature.
-
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 an error code, the build system will also
- return an 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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-In V1, there were two methods to configure a toolset. One was to
- set some environment variable, or use the -s
command line option to set
- a variable inside BJam.
-
- Another method was to create a new toolset module that would set
- the variables and then invoke the base toolset. Neither method
- is necessary now: the using
rule provides a consistent way to
- initialize a toolset,
-
- including several versions. See the section called “Configuration” for details.
-
Probably one of the most important differences in V2 Jamfiles is
- the use of project requirements. In V1, if several targets had the same
- requirements (for example, a common #include
path), it was necessary to
- manually write the requirements or use a helper rule or template target. In V2, the
- common properties can be specified with the requirements
project
- attribute, as documented in the section called “Projects”.
-
Usage requirements
- also help to simplify Jamfiles.
-
- If a library requires
- all clients to use specific #include
paths or macros when compiling
- code that depends on the library, that information can be cleanly
- represented.
The difference between lib
and dll
targets in V1 is completely
- eliminated in V2. There's only one library target type, lib
, which can create
- either static or shared libraries depending on the value of the
- <link>
- feature. If your target should be only built in one way, you
- can add <link>shared
or <link>static
to its 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 from the others by a double slash to indicate that
- you're referring to target bar
in project ../foo
, and not to
- project ../foo/bar
.
-
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 implicit features, just: -
--bjam msvc release some_target --
- See the reference for a - complete description of the syntax. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Jamfiles are the thing that is most important to the user, - - bacause they declare the targets that should be built. - - Jamfiles are also used for organizing targets— - - each Jamfile is a separate project - - that can be built independently from the other projects. -
-Jamfiles mostly contain calls to Boost.Build functions that do - all the work, specifically: -
- -- A Main target is a user-defined named - entity that can be built, for example an executable file. - - Declaring a main target is usually done using one of the main - target rules described in the section called “Builtin target types”. The user can also declare - custom main target rules as shown in the section called “Main target rules”. -
-Most main target rules in Boost.Build can be invoked with - a common syntax:
--rule-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. A main target name may contain
- alphanumeric characters, dashes
- (‘-
’), and underscores
- (‘_
’).
- 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, e.g. on the command line or by propogation from a dependent target.
- usage-requirements
is the list of properties that will be
- propagated to all main targets that use this one, i.e. to all its
- dependents.
- - Some main target rules have a shorter list of parameters; - consult their documentation for details. -
-Note that the actual requirements, default-build and - usage-requirements attributes for a target are obtained by - combining the explicitly specified ones with those specified for - the project where a target is declared. -
-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'll want to automatically construct the
- list of source files rather than having to spell it out
- manually, in which case you can use the
- glob
rule. Here are two examples:
-
-exe a : a.cpp ; # a.cpp is the only source file -exe b : [ glob *.cpp ] ; # all .cpp files in this directory are sources --
- Unless you specify a files with absolute path, the name is - considered relative to the source directory -- which is typically - the directory where the Jamfile is located, but can be changed as - described in the section called “Projects”. -
-- The list of sources can also refer to other main targets. - Targets in the same project can be referred to by name, while - targets in other projects need to be qualified with a directory or a symbolic - project name. For example: -
--lib helper : helper.cpp ; -exe a : a.cpp helper ; -exe b : b.cpp ..//utils ; -exe c : c.cpp /boost/program_options//program_options ; --
- 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, referring to it by its absolute symbolic name. More - information about it can be found in the section called “Dependent Targets” and the section called “Target identifiers and references”. -
-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 can only be built statically, 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. Conditional - properties can be used in that case: -
--lib util : util.cpp : <toolset>msvc:<link>static ; --
- Whenever <toolset>msvc
property is
- in build properties, the <link>static
property will
- be included as well. 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
parameter
-
- is a set of properties to be used if the build request does
- not otherwise specify a value for features in the set. For example:
-
-exe hello : hello.cpp : : <threading>multi ; --
- would build a multi-threaded target in unless the user - explicitly requests a 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 which - case each declaration is called an - alternative. When the target is built, one of - the alternatives will be selected and used. Alternatives need not be - defined by the same main target rule. For example, -
--lib helpers : helpers.hpp ; # a header-only library -alias helpers : helpers.lib : <toolset>msvc ; # except on msvc --
The actual commands used to build any given main target can differ greatly from - platform to platform. For example, you might have different lists - 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 themselves. -
-It is possible to declare a target inline, i.e. the "sources" - parameter may include calls 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.
-
- When referring to an inline main target, its declared name
- must be prefixed by its parent target's name and two dots. In
- the example above, to build only helpers, one should run
- bjam hello..helpers
.
-
As mentioned before, targets are grouped into projects, - and each Jamfile is a separate project. Projects are useful - because they allow us to group related targets together, define - properties common to all those targets, and assign a symbolic - name to the project that can be used in referring to its - targets. -
-Projects are named using the
- project
rule, which has the
- following syntax:
-
-project-id
:attributes
; -
- Here, attributes
is a sequence of
- rule arguments, each of which begins with an attribute-name
- and is followed by any number of build properties.
- 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 24.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 |
-Empty if the parent has no build directory set. - Otherwise, the parent's build directory with with the - relative path from parent to the current project - appended to it. - | -Sets to the passed value, interpreted as relative to the - project's location. | -
Besides defining projects and main targets, Jamfiles
- commonly invoke utility rules such as
- constant
and
- path-constant
, which inject a
- specified Boost.Jam variable setting into this project's Jamfile
- module and those of all its subprojects. See the section called “Jamfile Utility Rules” for a complete description
- of these utility rules. Jamfiles are regular Boost.Jam source
- files and Boost.Build modules, so naturally they can contain any kind of Boost.Jam code,
- including rule definitions.
-
Each subproject inherits attributes, constants and rules
- from its parent project, which is defined by the nearest
- Jamfile in an ancestor directory above
- the subproject. The top-level project is declared in a file
- called Jamroot
rather than
- Jamfile
. When loading a project,
- Boost.Build looks for either Jamroot
or
- Jamfile
. They are handled indentically, except
- that if the file is called Jamroot
, the
- search for a parent project is not performed.
-
Even when building in a subproject directory, parent
- project files are always loaded before those of their
- subprojects, so that every definition made in a parent project
- is always available to its children. The loading order of any
- other projects is unspecified. Even if one project refers to
- another via use-project
,
- or a target reference, no specific order should be assumed.
-
Giving the root project the special name
- “Jamroot
” ensures that
- Boost.Build won't misinterpret a directory above it as the
- project root just because the directory contains a Jamfile.
-
The following table describes utility rules that can be - used in Jamfiles. Detailed information for any of these rules can - be obtained by running: -
-
-bjam --help project.rulename
-Table 24.2.
-Rule | -Semantics | -
---|---|
project | -Define this project's symbolic ID or attributes. | -
use-project | -Make another project known so that it can be referred to by symbolic ID. | -
build-project | -Cause another project to be built when this one is built. | -
explicit | -State that a target should be built only by explicit - request. | -
glob | -Translate a list of shell-style wildcards into a - corresponding list of files. | -
constant | -Injects a variable setting into this project's - Jamfile module and those of all its subprojects. | -
path-constant | -Injects a variable set to a path value into - this project's Jamfile module and those of all its subprojects. - If the value is a relative path it will be adjusted for - each subproject so that it refers to the same - directory. | -
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
The build layer has just four main parts -- metatargets (abstract targets), - virtual targets, generators and properties. -
-Metatargets (see the "targets.jam" module) represent
- all the user-defined entities which can be built. The "meta" prefix
- signify that they don't really corrspond to files -- depending of
- build request, they can produce different set of
- files. Metatargets are created when Jamfiles are loaded. Each
- metagarget has a generate
method which is given a
- property set and produces virtual targets for the passed properties.
-
Virtual targets (see the "virtual-targets.jam" - module) correspond to the atomic things which can be updated -- - most typically files. -
Properties are just (name, value) pairs, specified
- by the user and describing how the targets should be
- built. Properties are stored using the property-set
class.
-
Generators are the objects which encapsulate tools - -- they can take a list of source virtual targets and produce new - virtual targets from them. -
The build process includes those steps: -
-Top-level code calls the generate
- method of a metatarget with some properties.
The metatarget combines the requested properties
- with requirements and passes the result, together with the list
- of sources, to the generators.construct
- function
A generator appropriate for the build properties is
- selected and its run
method is
- called. The method returns a list of virtual targets
-
The targets are returned to the top level code. They
- are converted into bjam targets (via
- virtual-target.actualize
) and passed to bjam for building.
-
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. -
-This means that a specific metatarget subclass may avoid using - generators at all. However, this is deprecated and we're trying to - eliminate all such subsclasses at the moment. -
-Note that the build/targets.jam
file contains
- an UML diagram which might help.
Virtual targets correspond to the atomic things which can be
- updated. Each virtual target can be assigned an updating action --
- instance of the action
class. The action class, in
- turn, contains a list of source targets, properties, and a name of
- bjam action block which should be executed.
-
We try hard to never create equal instances of the
- virtual-target
class. Each code which creates virtual
- targets passes them though the virtual-target.register
- function, which detects if a target with the same name, sources, and
- properties was created. In that case, existing target is returned.
-
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 the
- virtual-target.actualize
method and the
- 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. -
-Note that the build/virtual-targets.jam
file
- contains an UML diagram which might help.
Above, we noted that metatargets are built with a set of
- properties. That set is represented with the
- property-set
class. An important point is that handling
- of property sets can get very expensive. For that reason, we make
- sure that for each set of (name, value) pairs only one
- property-set
instance is created. The
- property-set
uses extensive caching for all operation,
- so most work is avoided. The property-set.create
is the
- factory function which should be used to create instances of the
- property-set
class.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 is the process of finding implicit - dependencies, like "#include" statements in C++. The requirements - for right dependency scanning mechanism are:
-Different scanning algorithm are encapsulated by objects - called "scanners". Please see the documentation for "scanner" - module for more details.
-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 --------------------------------+ --
This requirement breaks down to the following ones.
-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:
-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:
-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.
-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.
-- The remainder of this document is not indended to be read at - all. This will be rearranged in future. -
-
- 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.
-
To distinguish targets build with different properties, they - are put in different directories. Rules for determining target - paths are given below:
-<feature-name>-<feature-value>
for
- ordinary features and <feature-value>
for
- implicit ones. [Note about composite features].
- 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 --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -This document explains how to extend Boost.Build to accomodate - your local requirements. Let's start with a simple but - realistic example.
-Say you're writing an application that 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:
-It's quite easy to achieve. You write special verbatim files
- that are just C++, except that the very first line of the file
- contains the name of a variable that should be generated. A simple tool
- is created that takes a verbatim file and creates a cpp file with
- a single char*
variable whose name is taken from the first line
- of the verbatim file and whose value is the file's properly quoted content.
Let's see what Boost.Build can do.
-First off, Boost.Build has no idea about "verbatim files". So, - you must register a new target type. The following code does - it:
--import type ; -type.register VERBATIM : vrb ; --
The first parameter to
- type.register
gives the name of the
- declared type. By convention, it's uppercase. The second parameter
- is the suffix for files of this type. So, if Boost.Build sees
- code.vrb
in a list of sources, it knows that it's of type
- VERBATIM
.
Next, you tell Boost.Build that the verbatim files can be
- transformed into C++ files in one build step. A
- generator is a template for a build step that
- transforms targets of one type (or set of types) into another. Our
- generator will be called verbatim.inline-file
; it
- transforms VERBATIM
files into CPP
files:
-
-
-import generators ; -generators.register-standard verbatim.inline-file : VERBATIM : CPP ; --
Lastly, you have to inform Boost.Build about the shell
- commands used to make that transformation. That's done with an
- actions
declaration.
-
-
-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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- Often, we need to control the options passed the invoked tools. This - is done with features. Consider an example: -
--# Declare a new free 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 that 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 passed to the compiler's command line.
-
- Besides such portable features there are special 'raw' features that
- 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 you to pass any command line
- options to a C++ compiler. The <include>
feature
- allows you to pass any string preceded by -I
and the interpretation
- is tool-specific. (See the section called “Can I get output of external program as a variable in a Jamfile?
- ” for an example of very smart usage of that
- feature). Of course one should always strive to use portable
- features, but these are still be provided as a backdoor just to make
- sure Boost.Build does not take away any control from the user.
-
- Using portable features is a good idea because: -
-When a portable feature is given a fixed set of - values, you can build your project with two different - settings of the feature and Boost.Build will automatically - use two different directories for generated files. - Boost.Build does not try to separate targets built with - different raw options. -
Unlike with “raw” features, you don't need to use - specific command-line flags in your Jamfile, and it will be - more likely to work with other tools. -
Adding a feature requires three steps: - -
-Declaring a feature. For that, the "feature.feature" - rule is used. You have to decide on the set of feature - attributes: - -
-if a feature has several values and - significally affects the build, make it “propagated,” so that the - whole project is built with the same value by - default
if a feature does not have a fixed
- list of values, it must be “free.” For example, the
- include
feature is a free
- feature.
if a feature is used to refer to a
- path relative to the Jamfile, it must be a “path”
- feature. include
is also a path
- feature.
if feature is used to refer to some target, it - must be a “dependency” feature.
Representing the feature value in a
- target-specific variable. Build actions are command
- templates modified by Boost.Jam variable expansions. The
- toolset.flags
rule sets a target-specific
- variable to the value of a feature.
Using the variable. The variable set in step 2 can - be used in a build action to form command parameters or - files.
Here's another example. - Let's see how we can make a feature that 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... -
-Since the feature refers to a target, it must be "dependency". -
--feature def-file : : free dependency ; --
One of the toolsets that cares about - - DEF files is msvc. The following line should be added to it. -
--flags msvc.link DEF_FILE <def-file> ; --
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 to translate the internal target name in
- DEF_FILE
to a corresponding filename in
- the link
action. Without it the expansion of
- $(DEF_FILE)
would be a strange symbol that 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. -
-Sometimes you want to create a shorcut for some set of
- features. For example, release
is a value of
- <variant>
and is a shortcut for a set of features.
-
It is possible to define your own 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 that 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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- A main target rule (e.g “exe
”
- Or “lib
”) creates a top-level target. It's quite likely that you'll want to declare your own and
- there are two ways to do that.
-
The first way applies when
-
- your target rule should just produce a target of specific type. In that case, a
- rule is already defined for you! When you define a new type, Boost.Build
- automatically defines a corresponding rule. The name of the rule is
- obtained from the name of the type, by downcasing all letters and
- replacing underscores with dashes.
-
- For example, if you create a module
- obfuscate.jam
containing:
-
-
-import type ; -type.register OBFUSCATED_CPP : ocpp ; - -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 second way is to write a wrapper rule that calls - any of the existing rules. For example, suppose you have only one library per - directory and want all cpp files in the directory to be compiled into that library. You - can achieve this effect with: -
--lib codegen : [ glob *.cpp ] ; --
- but if you want to make it even simpler, you could 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 you to reduce the Jamfile to -
--glib codegen ; --
- Note that because you can associate a custom generator with a target
- type, the logic of building can be rather compiler.
-
- For example, the
- boostbook
module declares a target type
- BOOSTBOOK_MAIN
and a custom generator for that
- type. You can use that as example if your main target rule is
- non-trivial.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-
Sometimes you want to change the suffix used for generated targets
- depending on build properties, such as toolset. For example, some compiler
- uses extension elf
for executable files. You can use the
- type.set-generated-target-suffix
rule:
-
-type.set-generated-target-suffix EXE : <toolset>elf : elf ; --
A new target type can be inherited from an existing one. -
--type.register PLUGIN : : SHARED_LIB ; --
- The above code defines a new type derived from
- SHARED_LIB
. Initially, the new type inherits all the
- properties of the base type - in particular generators and suffix.
- Typically, you'll change the new type in some way. For example, using
- type.set-generated-target-suffix
you can set the suffix for
- the new type. Or you can write special generator for the new type. For
- example, it can generate additional metainformation for plugin.
- In either way, the PLUGIN
type can be used whenever
- SHARED_LIB
can. For example, you can directly link plugins
- to an application.
-
A type can be defined as "main", in which case Boost.Build will - automatically declare a main target rule for building targets of that - type. More details can be found later. -
-- 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 that 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. Only the
- first parenthesized group in the regular expression will be
- recognized; if you can't express everything you want that
- way, you can return multiple regular expressions, each of
- which contains a parenthesized group to be matched.
-
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 the properties that contain the list
- of paths that 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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 that it
- accepts an produces. Using that information, Boost.Build is able
- to automatically invoke the generator. For example, if you declare a
- generator that 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
with a 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 ; --
- Standard generators take 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)
-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
method is
- responsible for the 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 a real-life example,
- suppose you have a program analysis tool that 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 leaves ; - local temp = [ virtual-target.traverse $(sources[1]) : : include-sources ] ; - for local t in $(temp) - { - if ! [ $(t).action ] - { - leaves += $(t) ; - } - } - return [ generator.generated-targets $(sources) $(leafs) - : $(property-set) : $(project) $(name) ] ; - } -} -generators.register [ new itrace-generator nm.itrace : EXE : ITRACE ] ; --
- The generated-targets
method will be called with a single
- source target of type EXE
. The call to
- virtual-target.traverse
will return all targets the
- executable depends on, and we further find files that 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 that 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 ] ; # get the target's basename - if $(name) = [ $(python).name ] - { - name = $(name)_ext ; # rename the target - } - 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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
If your extensions will be used only on one project, they can be
- placed in a separate .jam
file that will be
- imported by your project-root.jam
. If the
- extensions will be used on many projects, users will thank you for
- a finishing touch.
-
The using
rule provides a standard mechanism
- for loading and configuring extensions. To make it work, your module
-
- should provide an init
rule. The rule will be called
- with the same parameters that 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 versions, and other options.
-
Here are some guidelines that help to make Boost.Build more - consistent: -
-The init
rule should never fail. Even if
- the user provided an incorrect 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 the command to be executed - to specifying the tool's installation 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's better if user doesn't have to remember whether - 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 the - tool's 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, 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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-dll-path
and
- hardcode-dll-paths
properties useful?
- - 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.
-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 ; --
- 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 ; --
- 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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
(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 your 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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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) ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- If you've just found out about Boost.Build V2 and want to know - if it will work for you, start with Chapter 23, Tutorial. You can continue with the Chapter 24, User documentation. When you're ready to try Boost.Build - in practice, go to Chapter 22, Installation. -
-- If you are about to use Boost.Build on your project, or already - using it and have a problem, look at Chapter 24, User documentation. -
-- If you're trying to build a project which uses Boost.Build, - look at Chapter 22, 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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- This section describes how to install Boost.Build from a
- released Boost
- source distribution
- or CVS
- image.
- [2]
-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.
- [3]
-
- 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. -
-user-config.jam
file in the Boost.Build
- root directory and follow the instructions there to describe
- your toolsets and libraries, and, if necessary, where they
- are located.
- 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: -
-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.
[2] Note that packages prepared for - Unix/Linux systems usually make their own choices about where to - put things and even which parts of Boost to include. When we - say “released source distribution” we mean a - distribution of Boost as released on its SourceForge - project - page. -
[3] The Boost.Build subset of boost is also distributed
- separately, for those who are only interested in getting a
- build tool. The top-level directory of a Boost.Build
- distribution contains all the subdirectories of the
- tools/build/v2
subdirectory from a full
- Boost distribution, so it is itself a valid Boost.Build root
- directory. It also contains the
- tools/build/jam_src
subdirectory of a
- full Boost distribution, so you can rebuild Boost.Jam from
- source.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-bjam's first job upon startup is to load the Jam code that
- 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
- that location and the directories in BOOST_BUILD_PATH are then searched for
- a file called bootstrap.jam
, which 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 26.1. Search paths for configuration files
-- | site-config.jam | -user-config.jam | -
---|---|---|
Linux | -
-
|
-
-
|
-
Windows | -
-
|
-
-
|
-
- Boost.Build comes with default versions of those files, - - which can serve as templates for customized versions. -
-The command line may contain:
-- Command line arguments specify targets and build - request using the following rules. -
-=
- symbol is either a value of an implicit feature or of a target to
- be built. It is taken to be value of a feature if an appropriate
- feature exists. Otherwise, it is considered a target id. Building the
- special target name “clean” has the same effect as
- using the --clean
option.
-
- An argument containing either slashes or
- the =
symbol specifies a number of build
- request elements (see ???). In its 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 --
- - A more complex form can be 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 combinations - - of the property sets. Each split - part should have the either the form - -
-feature-name=feature-value1[","feature-valueN]* --
- - or, in case of implicit features - -
-feature-value1[","feature-valueN;]* --
- - will be converted into the 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.
-
All of the Boost.Build options start with the "--" prefix. - They are described in the following table.
-Table 26.2. Command line options
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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: -
-applying default build,
selecting the main target alternative to use, -
determining "common" properties
building targets referred by the sources list and - dependency properties
adding the usage requirements produces when building - dependencies to the "common" properties
building the target using generators
computing the usage requirements to be returned
When there are several alternatives, one of them must be - selected. The process is as follows:
-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. -
-Non-free feature can have only one - value
A non-conditional property in requirement in always - present in common properties.
A property in build request is present in - common properties, unless (2) tells otherwise.
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.
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.
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 ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 that 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 that fully - describes the set of features used to build a target.
-
- 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
.
-
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 that 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? ] -
-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.
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 that is not required to - appear in a build specification. Every non-optional non-free - feature has a default value that 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 necessary. 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 that are neither free nor incidental are called - base features.
-- A build variant, or (simply variant) is a special kind of composite - feature that 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 ] -
-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
-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 ; --
The syntax also allows several properties in the condition, for - example: -
--exe hello : hello.cpp : <os>NT,<toolset>gcc:<link>static ; --
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 - -
-- - 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:
-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.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
Each generator, in addition to target types that it can - produce, have attribute that affects its applicability in - particular sitiation. Those attributes are:
-- 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 that 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.
-When generators are selected, each is run to produce a list of - created targets. This list might include targets that 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 that 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.
- 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. -
-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 that 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:
-- When dependency graph is constructed, each action can be - assigned a rule for property adjustment. -
- 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.
-- 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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
This section describes specific information about writing Jamfiles.
-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. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -The simplest project that Boost.Build can construct is
- stored in example/hello/
directory. The
- project is described by a file
- called Jamroot
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 hello
- executable by compiling and
- linking hello.cpp
. By default, debug variant
- is built. 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 unnecessary
- recompilation. Let's extend the example by adding another line
- to our project's Jamroot
:
-
-
-exe hello2 : hello.cpp ; --
- - Now let us build both the debug and release variants of our project - again: - -
--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 --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Sometimes, particular relationships need to be maintained
- among a target's build properties. This can be achieved with
- conditional
- requirement. For example, you might want to set
- specific #defines
when a library is built as shared,
- or when a target's release
variant is built in
- release mode.
-
-lib network : network.cpp
- : <link>shared:<define>NEWORK_LIB_SHARED
- <variant>release:<define>EXTRA_FAST
- ;
-
-
-
- In the example above, whenever network
is
- built with <link>shared
,
- <define>NEWORK_LIB_SHARED
will be in its
- properties, too.
-
- Sometimes the ways a target is built are so different that - describing them using conditional requirements would be - hard. For example, imagine that a library actually uses - different source files depending on the toolset used to build - it. We can express this situation using target - alternatives: -
--lib demangler : dummy_demangler.cpp ; # alternative 1 -lib demangler : demangler_gcc.cpp : <toolset>gcc ; # alternative 2 -lib demangler : demangler_msvc.cpp : <toolset>msvc ; # alternative 3 --
- In the example above, when built with gcc
- or msvc
, demangler
- will use a source file specific to the toolset. Otherwise, it
- will use a generic source file,
- dummy_demangler.cpp
.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
So far we've only considered examples with one project
- (i.e. with one user-written Boost.Jam file,
- Jamroot
). A typical large codebase would be
- composed of many projects organized into a tree. The top of the
- tree is called the project root. Every
- subproject is defined by a file called
- Jamfile
in a descendant directory of the
- project root. The parent project of a subproject is defined by
- the nearest Jamfile
or
- Jamroot
file in an ancestor directory. For
- example, in the following directory layout:
-
-
-top/ - | - +-- Jamroot - | - +-- app/ - | | - | +-- 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/app/
and
- top/util/foo/
are immediate children of the
- root project.
-
-
- When we refer to a “Jamfile,” set in normal
- type, we mean a file called either
- Jamfile
or
- Jamroot
. When we need to be more
- specific, the filename will be set as
- “Jamfile
” or
- “Jamroot
.”
-
- 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/Jamroot
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 - include paths to those specified by its parents. [5] - More details can be found in - the section called “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/Jamroot
might contain:
-
-
-build-project app ; --
-
- which would cause the project in top/app/
- 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/app/
.
-
[5] Many - features will be overridden, - rather than added-to, in sub-projects. See the section called “Feature Attributes” for more - information
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 top/app/Jamfile
can
- use libraries from top/util/foo
. If
- top/util/foo/Jamfile
contains
-
-
-lib bar : bar.cpp ; --
-
- then to use this library in top/app/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
.
-
Some other build system have special syntax for listing dependent
- libraries, for example LIBS
variable. In Boost.Build,
- you just add the library to the list of sources.
-
Suppose we build app
with:
-
-bjam app optimization=full define=USE_ASM --
- Which properties will be used to build foo
? The answer is
- that some features 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 <define>
is not
- propagated: its value will be added as-is to the compiler flags for
- a.cpp
, but won't affect foo
.
-
Let's improve this project further.
- The library
- probably has some headers that must be used when compiling
- app.cpp
. We could manually add the necessary
- #include
paths to app
's
- requirements as values of the
- <include>
feature, but then this work will
- be repeated for all programs
- that use foo
. A better solution is to modify
- util/foo/Jamfile
in this way:
-
-
-project - : usage-requirements <include>. - ; - -lib foo : foo.cpp ; --
-
- Usage requirements are applied not to the target being declared
- but to its
- dependents. In this case, <include>.
will be applied to all
- targets that directly depend on foo
.
-
Another improvement is using symbolic identifiers to refer to
- the library, as opposed to Jamfile
location.
- In a large project, a library can be used by many targets, and if
- they all use Jamfile
location,
- a change in directory organization entails much work.
- The solution is to use project ids—symbolic names
- not tied to directory layout. First, we need to assign a project id by
- adding this code to
- Jamroot
:
-use-project /library-example/foo : util/foo ; --
Second, we modify app/Jamfile
to use the
- project id:
-
-
-exe app : app.cpp /library-example/foo//bar ; --
-The /library-example/foo//bar
syntax is used
- to refer to the target bar
in
- the project with id /library-example/foo
.
- We've achieved our goal—if the library is moved to a different
- directory, only Jamroot
must be modified.
- Note that project ids are global—two Jamfiles are not
- allowed to assign the same project id to different directories.
-
-
If you want all applications in some project to link
- to a certain library, you can avoid having to specify it directly the sources of every
- target 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 the project's requirements, like this:
-project - : requirements <source>/boost/filesystem//fs - ; --
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Libraries can be either - static, which means they are included in executable - files that 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 create and use both kinds. -
-The kind of library produced from a lib
target is
- determined by the value of the link
feature. Default
- value is shared
, and to build static library, the value
- should be static
. You can either requiest static build
- on the command line:
-
-bjam link=static --
- or in the library's requirements: -
--lib l : l.cpp : <link>static ; --
- We can also use the <link>
property
- to express linking requirements on a per-target basis.
- For example, if a particular executable can be correctly built
- only with the static version of a library, we can qualify the
- executable's target
- reference to the library as follows:
-
-
-exe important : main.cpp helpers/<link>static ;-
-
- No matter what arguments are specified on the bjam
- command-line, important
will only be linked with
- the static version of helpers
.
-
- Specifying properties in target references is especially useful if you - use a library defined in some other project (one you can't - change) but you still want static (or dynamic) linking to that library - in all cases. If that library is used by many targets, - you could 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. A better approach is
- to introduce a level of indirection. Create a local
- alias target that refers to the static (or
- dynamic) version of foo
:
-
-
-alias foo : /other_project//bar/<link>static ; -exe e1 : e1.cpp foo ; -exe e10 : e10.cpp foo ;-
-
- The alias
- rule is specifically used to rename a reference to a target and possibly
- change the properties.
-
-
- When one library uses another, you put the second library is - the source list of the first. For example: -
--lib utils : utils.cpp /boost/filesystem//fs ; -lib core : core.cpp utils ; -exe app : app.cpp core ;-
- This works no matter what kind of linking is used. When
- core
is built as a shared library, it is linked
- directly into utils
. Static libraries can't
- link to other libraries, so when core
is built
- as a static library, its dependency on utils
is passed along to
- core
's dependents, causing
- app
to be linked with both
- core
and utils
."
-
(Note for non-UNIX system). Typically, shared libraries must be
- installed to a directory in the dynamic linker's search
- path. Otherwise, applications that use shared libraries can't be
- started. On Windows, the dynamic linker's search path is given by the
- PATH
environment variable. This restriction is lifted
- when you use Boost.Build testing facilities—the
- PATH
variable will be automatically adjusted before
- running executable.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- To link to libraries whose build instructions aren't given in a Jamfile,
- you need to create lib
targets with an appropriate
- file
property. Target alternatives can be used to
- associate multiple library files with a single conceptual target. For
- example:
-
-# util/lib2/Jamfile -lib lib2 - : - : <file>lib2_release.a <variant>release - ; - -lib lib2 - : - : <file>lib2_debug.a <variant>debug - ; --
-
- This example defines two alternatives for 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.
-
- Once a prebuilt target has been declared, it can be used just like any other target: - -
--exe app : app.cpp ../util/lib2//lib2 ; --
-
- As with any target, the alternative selected depends on the
- properties propagated from lib2
's dependents.
- If we build the the release and debug versions of app
will be linked
- with lib2_release.a
and lib2_debug.a
, respectively.
-
-
- System libraries—those that are automatically found by - the toolset by searching through some set of predetermined - paths—should be declared almost like regular ones: - -
--lib pythonlib : : <name>python22 ; --
-
- We again don't specify any sources, but give a
- name
that should be passed to the
- compiler. If the gcc toolset were used to link an executable
- target to pythonlib
, -lpython22
- would appear in the command line (other compilers may use
- different options).
-
- We can also specify where the toolset should look for the library: - -
--lib pythonlib : : <name>python22 <search>/opt/lib ; --
- - And, of course, target alternatives can be used in the usual way: - -
--lib pythonlib : : <name>python22 <variant>release ; -lib pythonlib : : <name>python22_d <variant>debug ; --
A more advanced use of prebuilt targets is described in the section called “Targets in site-config.jam”. -
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 in the section called “Features and properties”. -
-
- The set of properties specified on 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 are typically a
- combination of the build request and properties derived from
- the project's Jamroot
(and its other
- Jamfiles, as described in the section called “Project Hierarchies”). For example, the
- locations of #include
d 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>boost <threading>multi - ; --
- When hello
is built, the two
- requirements specified above will always be present.
- If the build request given on the bjam
- command-line explictly contradicts a target's requirements,
- the target requirements usually override (or, in the case of
- “free” features like
- <include>
,
- [4]
- augments) the build request.
-
-
The value of the <include>
feature is
- relative to the location of Jamroot
where it's
- used.
-
- 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 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
.
-
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::any — A class whose instances can hold instances of any - type that satisfies ValueType - requirements.
--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; -};
any
construct/copy/destructany();-
Postconditions:
-
- this->empty()
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.
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.
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.
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.
~any();-
Effects:
-
- Releases any and all resources used in
- management of instance.
Throws:
-
- Nothing.
any
queriesbool empty() const;-
Returns:
-
- true
if instance is
- empty, otherwise false
.
Throws:
-
- Will not throw.
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.
- | Copyright © 2001 Kevlin Henney | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::array —
STL compliant container wrapper for arrays of constant size
-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>&);
array
reverse iterator supportreverse_iterator rbegin(); -const_reverse_iterator rbegin() const;-
Returns: - - reverse iterator for the first element of reverse iteration
-reverse_iterator rend(); -const_reverse_iterator rend() const;-
Returns: - - reverse iterator for position after the last element in reverse iteration
-array
element accessreference operator[](size_type i); -const_reference operator[](size_type i) const;-
Requires:
-
- i < N
Returns:
-
- element with index i
Throws:
-
- will not throw.
reference at(size_type i); -const_reference at(size_type i) const;-
Returns:
-
- element with index i
Throws:
-
- std::range_error
if i >= N
reference front(); -const_reference front() const;-
Requires:
-
- N > 0
Returns:
-
- the first element
Throws:
-
- will not throw
reference back(); -const_reference back() const;-
Requires:
-
- N > 0
Returns:
-
- the last element
Throws:
-
- will not throw
const T* data() const;-
Returns:
-
- elems
Throws:
-
- will not throw
T* c_array();-
Returns:
-
- elems
Throws:
-
- will not throw
array
comparisonstemplate<typename T, std::size_t N> - bool operator==(const array<T, N>& x, const array<T, N>& y);- -
template<typename T, std::size_t N> - bool operator!=(const array<T, N>& x, const array<T, N>& y);-
Returns:
-
- !(x == y)
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())
template<typename T, std::size_t N> - bool operator>(const array<T, N>& x, const array<T, N>& y);-
Returns:
-
- y < x
template<typename T, std::size_t N> - bool operator<=(const array<T, N>& x, const array<T, N>& y);-
Returns:
-
- !(y < x)
template<typename T, std::size_t N> - bool operator>=(const array<T, N>& x, const array<T, N>& y);-
Returns:
-
- !(x < y)
- | Copyright © 2001-2004 Nicolai M. Josuttis | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date — Representation of timepoint at the one day level resolution.
-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 -};
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/destructdate(year_type y, month_type m, day_type d);
date(const ymd_type & ymd);
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.
-date(date_rep_type days);
date
public member functionsyear_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 & rhs) const;
bool operator==(const date_type & rhs) 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 & d) const;
date_type operator-(const duration_type & dd) const;
date_type operator-=(const duration_type & dd) ;
date_rep_type day_count() const;
date_type operator+(const duration_type & dd) const;
date_type operator+=(const duration_type & dd) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::function — A generalized function pointer that can be used for - callbacks or wrapping function objects.
-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>&);
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/destructfunction();-
Postconditions:
-
- this->empty()
Throws:
-
- Will not throw.
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.
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.
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.
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.
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.
~function();-
Effects:
-
- If !this->empty()
, destroys the target of this
.
function
capacitybool empty() const;-
Returns:
-
- false
if this
has a target, and true
otherwise.
Throws:
-
- Will not throw.
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.
bool operator!() const;-
Returns:
-
- this->empty()
Throws:
-
- Will not throw.
function
target accesstemplate<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.
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
invocationresult_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
comparison operatorstemplate<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)
.function
- objects are not
- EqualityComparable.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.
-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)
.function
- objects are not
- EqualityComparable.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.
-- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::date — A date type based on gregorian_calendar.
--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; - date end_of_month() const; -};
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
public member functionsdate_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;
date end_of_month() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash — An STL compliant hash function object.
-template<typename T> -struct hash : public std::unary_function<T, std::size_t> { - std::size_t operator()(T const&) const; -};
std::size_t operator()(T const& val) const;-
Returns: - -
hash_value(val)
hash_value
- is unqualified, so that custom overloads can be
- found via argument dependent lookup.
- hash_value(T)
throws.
-
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::tribool — A 3-state boolean type.
--class tribool { -public: - // construct/copy/destruct - tribool(); - tribool(bool); - tribool(indeterminate_keyword_t); - - // public member functions - operator safe_bool() const; - - enum boost::logic::tribool::value_t value; -};
3-state boolean values are either true, false, or indeterminate.
-tribool
construct/copy/destructtribool();-
Construct a new 3-state boolean value with the value 'false'.
- -Throws: - - Will not throw.
-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.
-tribool(indeterminate_keyword_t );-
Construct a new 3-state boolean value with an indeterminate value.
- -Throws: - - Will not throw.
-- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::variant — Safe, generic, stack-based discriminated union container.
-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; -};
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:
-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
.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.variant
must meet the requirements of the
- BoundedType
- concept.variant
must be distinct after removal of qualifiers.
- Thus, for instance, both variant<int, int>
and
- variant<int, const int>
have undefined
- behavior.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/destructvariant();-
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
.
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.
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.
template<typename T> variant(const T & operand);-
Notes: - - Same semantics as previous constructor, but allows - construction from temporaries.
-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.
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.
-~variant();-
Effects:
-
- Destroys the content of *this
.
Throws:
-
- Will not throw.
variant
modifiersvoid 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?).
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?).
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.).*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
.*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
queriesint 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.
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.
const std::type_info & type() const;-
Returns:
-
- typeid(x)
, where x
is the the
- content of *this
.
Throws:
-
- Will not throw.
variant
relationalbool 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()
andcontent_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
.
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
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2000, 2005 Steve Cleary and John Maddock
- 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 - ) - -
-Table of Contents
- -
-The header <boost/static_assert.hpp>
supplies a single macro BOOST_STATIC_ASSERT(x)
,
-which generates a compile time error message if the integral-constant-expression x
-is not true. In other words it is the compile time equivalent of the assert macro;
-this is sometimes known as a "compile-time-assertion", but will be called a
-"static assertion" throughout these docs. Note that if the condition is true
,
-then the macro will generate neither code nor data - and the macro can also
-be used at either namespace, class or function scope. When used in a template,
-the static assertion will be evaluated at the time the template is instantiated;
-this is particularly useful for validating template parameters.
-One of the aims of BOOST_STATIC_ASSERT
is to generate readable error messages.
-These immediately tell the user that a library is being used in a manner that
-is not supported. While error messages obviously differ from compiler to compiler,
-but you should see something like:
Illegal use of STATIC_ASSERTION_FAILURE<false>
--Which is intended to at least catch the eye!
-
-You can use BOOST_STATIC_ASSERT
at any place where you can place a declaration,
-that is at class, function or namespace scope, this is illustrated by the
-following examples:
-The macro can be used at namespace scope, if there is some requirement must
-always be true; generally this means some platform specific requirement.
-Suppose we require that int
be at least a 32-bit integral type, and that wchar_t
-be an unsigned type. We can verify this at compile time as follows:
#include <climits>
-#include <cwchar>
-#include <boost/static_assert.hpp>
-
-namespace my_conditions {
-
- BOOST_STATIC_ASSERT(sizeof(int) * CHAR_BIT >= 32);
- BOOST_STATIC_ASSERT(WCHAR_MIN >= 0);
-
-} // namespace my_conditions
-
-
-The use of the namespace my_conditions here requires some comment.
-The macro BOOST_STATIC_ASSERT
works by generating an typedef declaration,
-and since the typedef must have a name, the macro generates one automatically by
-mangling a stub name with the value of _LINE_. When BOOST_STATIC_ASSERT
is
-used at either class or function scope then each use of BOOST_STATIC_ASSERT
-is guaranteed to produce a name unique to that scope (provided you only use
-the macro once on each line). However when used in a header at namespace
-scope, that namespace can be continued over multiple headers, each of which
-may have their own static assertions, and on the "same" lines, thereby generating
-duplicate declarations. In theory the compiler should silently ignore duplicate
-typedef declarations, however many do not do so (and even if they do they are
-entitled to emit warnings in such cases). To avoid potential problems, if you
-use BOOST_STATIC_ASSERT
in a header and at namespace scope, then enclose
-them in a namespace unique to that header.
-The macro is typically used at function scope inside template functions, -when the template arguments need checking. Imagine that we have an -iterator-based algorithm that requires random access iterators. -If the algorithm is instantiated with iterators that do not meet our -requirements then an error will be generated eventually, but this may -be nested deep inside several templates, making it hard for the user to -determine what went wrong. One option is to add a static assertion at -the top level of the template, in that case if the condition is not met, -then an error will be generated in a way that makes it reasonably obvious to -the user that the template is being misused.
-#include <iterator>
-#include <boost/static_assert.hpp>
-#include <boost/type_traits.hpp>
-
-template <class RandomAccessIterator >
-RandomAccessIterator foo(RandomAccessIterator from, RandomAccessIterator to)
-{
- // this template can only be used with
- // random access iterators...
- typedef typename std::iterator_traits< RandomAccessIterator >::iterator_category cat;
- BOOST_STATIC_ASSERT((boost::is_convertible<cat, const std::random_access_iterator_tag&>::value));
- //
- // detail goes here...
- return from;
-}
-
-A couple of footnotes are in order here: the extra set of parenthesis around the
-assert, is to prevent the comma inside the is_convertible
template being
-interpreted by the preprocessor as a macro argument separator; the target type
-for is_convertible
is a reference type, as some compilers have problems
-using is_convertible
when the conversion is via a user defined constructor
-(in any case there is no guarantee that the iterator tag classes are
-copy-constructible).
-The macro is typically used inside classes that are templates. -Suppose we have a template-class that requires an unsigned integral type with -at least 16-bits of precision as a template argument, we can achieve this -using something like this:
-#include <climits>
-#include <boost/static_assert.hpp>
-
-template <class UnsignedInt>
-class myclass
-{
-private:
- BOOST_STATIC_ASSERT(sizeof(UnsignedInt) * CHAR_BIT >= 16);
- BOOST_STATIC_ASSERT(std::numeric_limits<UnsignedInt>::is_specialized
- && std::numeric_limits<UnsignedInt>::is_integer
- && !std::numeric_limits<UnsignedInt>::is_signed);
-public:
- /* details here */
-};
--Normally static assertions when used inside a class or function template, -will not be instantiated until the template in which it is used is instantiated. -However, there is one potential problem to watch out for: if the static assertion -is not dependent upon one or more template parameters, then the compiler is -permitted to evaluate the static assertion at the point it is first seen, -irrespective of whether the template is ever instantiated, for example:
-template <class T>
-struct must_not_be_instantiated
-{
- BOOST_STATIC_ASSERT(false);
-};
--Will produce a compiler error with some compilers (for example Intel 8.1 -or gcc 3.4), regardless of whether the template is ever instantiated. A -workaround in cases like this is to force the assertion to be dependent -upon a template parameter:
-template <class T>
-struct must_not_be_instantiated
-{
- // this will be triggered if this type is instantiated
- BOOST_STATIC_ASSERT(sizeof(T) == 0);
-};
-Last revised: April 17, 2005 at 10:45:13 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_STATIC_ASSERT
works as follows. There is class STATIC_ASSERTION_FAILURE
- which is defined as:
namespace boost{
-
-template <bool> struct STATIC_ASSERTION_FAILURE;
-
-template <> struct STATIC_ASSERTION_FAILURE<true>{};
-
-}
-
-The key feature is that the error message triggered by the undefined
-expression sizeof(STATIC_ASSERTION_FAILURE<0>)
, tends to be consistent
-across a wide variety of compilers. The rest of the machinery of
-BOOST_STATIC_ASSERT
is just a way to feed the sizeof
expression into a typedef
.
-The use of a macro here is somewhat ugly; however boost members have spent
-considerable effort trying to invent a static assert that avoided macros,
-all to no avail. The general conclusion was that the good of a static assert
-working at namespace, function, and class scope outweighed the ugliness of a macro.
- | Copyright © 2000, 2005 Steve Cleary and John Maddock | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Test Program | -Expected to Compile | -Description | -
---|---|---|
static_assert_test.cpp | -Yes | -Illustrates usage, and should always compile, really just tests compiler compatibility. | -
static_assert_example_1.cpp | -Platform dependent. | -Namespace scope test program, may compile depending upon the platform. | -
static_assert_example_2.cpp | -Yes | -Function scope test program. | -
static_assert_example_3.cpp | -Yes | -Class scope test program. | -
static_assert_test_fail_1.cpp | -No | -Illustrates failure at namespace scope. | -
static_assert_test_fail_2.cpp | -No | -Illustrates failure at non-template function scope. | -
static_assert_test_fail_3.cpp | -No | -Illustrates failure at non-template class scope. | -
static_assert_test_fail_4.cpp | -No | -Illustrates failure at non-template class scope. | -
static_assert_test_fail_5.cpp | -No | -Illustrates failure at template class scope. | -
static_assert_test_fail_6.cpp | -No | -Illustrates failure at template class member function scope. | -
static_assert_test_fail_7.cpp | -No | -Illustrates failure of class scope example. | -
static_assert_test_fail_8.cpp | -No | -Illustrates failure of function scope example. | -
static_assert_test_fail_9.cpp | -No | -Illustrates failure of function scope example (part 2). | -
- | Copyright © 2000, 2005 Steve Cleary and John Maddock | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek
- 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 - ) - -
-Table of Contents
--The Boost type-traits library contains a -set of very specific traits classes, each of which encapsulate a single trait -from the C++ type system; for example, is a type a pointer or a reference type? -Or does a type have a trivial constructor, or a const-qualifier?
--The type-traits classes share a unified design: each class inherits from a -the type true_type if the type has the specified property and inherits from -false_type otherwise.
-
-The type-traits library also contains a set of classes that perform a
-specific transformation on a type; for example, they can remove a
-top-level const or volatile qualifier from a type. Each class that
-performs a transformation defines a single typedef-member type
-that is the result of the transformation.
Last revised: May 11, 2005 at 14:32:21 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-The following is an updated version of the article "C++ Type traits" -by John Maddock and Steve Cleary that appeared in the October 2000 -issue of Dr Dobb's Journal.
--Generic programming (writing code which works with any data type meeting a -set of requirements) has become the method of choice for providing reusable code. -However, there are times in generic programming when "generic" just isn't -good enough - sometimes the differences between types are too large for an -efficient generic implementation. This is when the traits technique -becomes important - by encapsulating those properties that need to be -considered on a type by type basis inside a traits class, we can -minimize the amount of code that has to differ from one type to another, -and maximize the amount of generic code.
-
-Consider an example: when working with character strings, one common operation is
-to determine the length of a null terminated string. Clearly it's possible to
-write generic code that can do this, but it turns out that there are much more
-efficient methods available: for example, the C library functions strlen
and
-wcslen
are usually written in assembler, and with suitable hardware support
-can be considerably faster than a generic version written in C++.
-The authors of the C++ standard library realized this, and abstracted the
-properties of char
and wchar_t
into the class char_traits
. Generic code
-that works with character strings can simply use char_traits<>::length
to
-determine the length of a null terminated string, safe in the knowledge
-that specializations of char_traits
will use the most appropriate method
-available to them.
-Class char_traits
is a classic example of a collection of type specific
-properties wrapped up in a single class - what Nathan Myers termed a
-baggage class[1]. In the Boost type-traits library, we[2] have written a
-set of very specific traits classes, each of which encapsulate a single trait
-from the C++ type system; for example, is a type a pointer or a reference type?
-Or does a type have a trivial constructor, or a const-qualifier?
-The type-traits classes share a unified design: each class inherits from a
-the type true_type if the type has the specified property and inherits from
-false_type otherwise. As we will show, these classes can be used in
-generic programming to determine the properties of a given type and introduce
-optimizations that are appropriate for that case.
-The type-traits library also contains a set of classes that perform a
-specific transformation on a type; for example, they can remove a
-top-level const or volatile qualifier from a type. Each class that
-performs a transformation defines a single typedef-member type
-that is the result of the transformation. All of the type-traits
-classes are defined inside namespace boost
; for brevity, namespace-qualification
-is omitted in most of the code samples given.
-There are far too many separate classes contained in the type-traits library
-to give a full implementation here - see the source code in the Boost library
-for the full details - however, most of the implementation is fairly repetitive
-anyway, so here we will just give you a flavor for how some of the classes are
-implemented. Beginning with possibly the simplest class in the library,
-is_void<T>
inherits from true_type
only if T
is void
.
template <typename T>
-struct is_void : public false_type{};
-
-template <>
-struct is_void<void> : public true_type{};
-
-Here we define a primary version of the template class is_void
, and
-provide a full-specialization when T
is void
. While full specialization
-of a template class is an important technique, sometimes we need a
-solution that is halfway between a fully generic solution, and a full
-specialization. This is exactly the situation for which the standards committee
-defined partial template-class specialization. As an example, consider the
-class boost::is_pointer<T>
: here we needed a primary version that handles
-all the cases where T is not a pointer, and a partial specialization to
-handle all the cases where T is a pointer:
template <typename T>
-struct is_pointer : public false_type{};
-
-template <typename T>
-struct is_pointer<T*> : public true_type{};
--The syntax for partial specialization is somewhat arcane and could easily -occupy an article in its own right; like full specialization, in order to -write a partial specialization for a class, you must first declare the -primary template. The partial specialization contains an extra <...> after the -class name that contains the partial specialization parameters; these define -the types that will bind to that partial specialization rather than the -default template. The rules for what can appear in a partial specialization -are somewhat convoluted, but as a rule of thumb if you can legally write two -function overloads of the form:
-void foo(T);
-void foo(U);
--Then you can also write a partial specialization of the form:
-template <typename T>
-class c{ /*details*/ };
-
-template <typename T>
-class c<U>{ /*details*/ };
--This rule is by no means foolproof, but it is reasonably simple to remember -and close enough to the actual rule to be useful for everyday use.
-
-As a more complex example of partial specialization consider the class
-remove_extent<T>
. This class defines a single typedef-member type
that
-is the same type as T but with any top-level array bounds removed;
-this is an example of a traits class that performs a transformation on a type:
template <typename T>
-struct remove_extent
-{ typedef T type; };
-
-template <typename T, std::size_t N>
-struct remove_extent<T[N]>
-{ typedef T type; };
-
-The aim of remove_extent
is this: imagine a generic algorithm that is
-passed an array type as a template parameter, remove_extent
provides a
-means of determining the underlying type of the array. For example
-remove_extent<int[4][5]>::type
would evaluate to the type int[5]
.
-This example also shows that the number of template parameters in a
-partial specialization does not have to match the number in the
-default template. However, the number of parameters that appear after the
-class name do have to match the number and type of the parameters in the
-default template.
-As an example of how the type traits classes can be used, consider the -standard library algorithm copy:
-template<typename Iter1, typename Iter2>
-Iter2 copy(Iter1 first, Iter1 last, Iter2 out);
-
-Obviously, there's no problem writing a generic version of copy that works
-for all iterator types Iter1
and Iter2
; however, there are some
-circumstances when the copy operation can best be performed by a call to
-memcpy
. In order to implement copy in terms of memcpy
all of the
-following conditions need to be met:
Iter1
and Iter2
must be pointers.
-Iter1
and Iter2
must point to the same type - excluding const and
-volatile-qualifiers.
-Iter1
must have a trivial assignment operator.
--By trivial assignment operator we mean that the type is either a scalar type[3] or:
-
-If all these conditions are met then a type can be copied using memcpy
-rather than using a compiler generated assignment operator. The type-traits
-library provides a class has_trivial_assign
, such that
-has_trivial_assign<T>::value
is true only if T has a trivial assignment operator.
-This class "just works" for scalar types, but has to be explicitly
-specialised for class/struct types that also happen to have a trivial assignment
-operator. In other words if has_trivial_assign gives the wrong answer,
-it will give the "safe" wrong answer - that trivial assignment is not allowable.
-The code for an optimized version of copy that uses memcpy
where appropriate is
-given in the examples. The code begins by defining a template
-function do_copy
that performs a "slow but safe" copy. The last parameter passed
-to this function may be either a true_type
or a false_type
. Following that
-there is an overload of do_copy that uses memcpy
: this time the iterators are required
-to actually be pointers to the same type, and the final parameter must be a
-true_type
. Finally, the version of copy
calls do_copy
, passing
-has_trivial_assign<value_type>()
as the final parameter: this will dispatch
-to the optimized version where appropriate, otherwise it will call the
-"slow but safe version".
-It has often been repeated in these columns that "premature optimization is the -root of all evil" [4]. So the question must be asked: was our optimization -premature? To put this in perspective the timings for our version of copy -compared a conventional generic copy[5] are shown in table 1.
--Clearly the optimization makes a difference in this case; but, to be fair, -the timings are loaded to exclude cache miss effects - without this -accurate comparison between algorithms becomes difficult. However, perhaps -we can add a couple of caveats to the premature optimization rule:
-Version | -T | -Time | -
---|---|---|
"Optimized" copy | -char | -0.99 | -
Conventional copy | -char | -8.07 | -
"Optimized" copy | -int | -2.52 | -
Conventional copy | -int | -8.02 | -
-The optimized copy example shows how type traits may be used to perform -optimization decisions at compile-time. Another important usage of type traits -is to allow code to compile that otherwise would not do so unless excessive -partial specialization is used. This is possible by delegating partial -specialization to the type traits classes. Our example for this form of -usage is a pair that can hold references [6].
-
-First, let us examine the definition of std::pair
, omitting the
-comparison operators, default constructor, and template copy constructor for
-simplicity:
template <typename T1, typename T2>
-struct pair
-{
-typedef T1 first_type;
-typedef T2 second_type;
-
-T1 first;
-T2 second;
-
-pair(const T1 & nfirst, const T2 & nsecond)
-:first(nfirst), second(nsecond) { }
-};
--Now, this "pair" cannot hold references as it currently stands, because the -constructor would require taking a reference to a reference, which is -currently illegal [7]. Let us consider what the constructor's parameters -would have to be in order to allow "pair" to hold non-reference types, -references, and constant references:
-Type of T1
- |
-Type of parameter to initializing constructor | -
---|---|
T | -const T & | -
T & | -T & | -
const T & | -const T & | -
-A little familiarity with the type traits classes allows us to construct a -single mapping that allows us to determine the type of parameter from the -type of the contained class. The type traits classes provide a -transformation add_reference, which adds a reference to its type, -unless it is already a reference.
-Type of T1
- |
-Type of const T1
- |
-Type of add_reference<const T1>::type
- |
-
---|---|---|
T | -const T | -const T & | -
T & | -T & [8] | -T & | -
const T & | -const T & | -const T & | -
-This allows us to build a primary template definition for pair
that can
-contain non-reference types, reference types, and constant reference types:
template <typename T1, typename T2>
-struct pair
-{
-typedef T1 first_type;
-typedef T2 second_type;
-
-T1 first;
-T2 second;
-
-pair(boost::add_reference<const T1>::type nfirst,
- boost::add_reference<const T2>::type nsecond)
-:first(nfirst), second(nsecond) { }
-};
-
-Add back in the standard comparison operators, default constructor,
-and template copy constructor (which are all the same), and you have a
-std::pair
that can hold reference types!
-This same extension could have been done using partial template specialization
-of pair
, but to specialize pair
in this way would require three partial
-specializations, plus the primary template. Type traits allows us to
-define a single primary template that adjusts itself auto-magically to
-any of these partial specializations, instead of a brute-force partial
-specialization approach. Using type traits in this fashion allows
-programmers to delegate partial specialization to the type traits classes,
-resulting in code that is easier to maintain and easier to understand.
-We hope that in this article we have been able to give you some idea of -what type-traits are all about. A more complete listing of the available -classes are in the boost documentation, along with further examples using -type traits. Templates have enabled C++ uses to take the advantage of the -code reuse that generic programming brings; hopefully this article has -shown that generic programming does not have to sink to the lowest common -denominator, and that templates can be optimal as well as generic.
--The authors would like to thank Beman Dawes and Howard Hinnant for their -helpful comments when preparing this article.
-- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-These traits are all value traits, which is to say the traits classes all
-inherit from integral_constant, and are used to access some numerical
-property of a type. Often this is a simple true or false Boolean value,
-but in a few cases may be some other integer value (for example when dealing
-with type alignments, or array bounds: see alignment_of
, rank
and extent
).
-These traits identify what "kind" of type some type T
is. These are split into
-two groups: primary traits which are all mutually exclusive, and composite traits
-that are compositions of one or more primary traits.
-For any given type, exactly one primary type trait will inherit from -true_type, and all the others will inherit from false_type, in other -words these traits are mutually exclusive.
-
-This means that is_integral<T>::value
and is_floating_point<T>::value
-will only ever be true for built-in types; if you want to check for a
-user-defined class type that behaves "as if" it is an integral or floating point type,
-then use the std::numeric_limits template
instead.
Synopsis:
-template <class T>
-struct is_array<T>;
-
-template <class T>
-struct is_class<T>;
-
-template <class T>
-struct is_enum<T>;
-
-template <class T>
-struct is_floating_point<T>;
-
-template <class T>
-struct is_function<T>;
-
-template <class T>
-struct is_integral<T>;
-
-template <class T>
-struct is_member_function_pointer<T>;
-
-template <class T>
-struct is_member_object_pointer<T>;
-
-template <class T>
-struct is_pointer<T>;
-
-template <class T>
-struct is_reference<T>;
-
-template <class T>
-struct is_union<T>;
-
-template <class T>
-struct is_void<T>;
--The following traits are made up of the union of one or more type -categorizations. A type may belong to more than one of these categories, -in addition to one of the primary categories.
-template <class T>
-struct is_arithmetic;
-
-template <class T>
-struct is_compound;
-
-template <class T>
-struct is_fundamental;
-
-template <class T>
-struct is_member_pointer;
-
-template <class T>
-struct is_object;
-
-template <class T>
-struct is_scalar;
--The following templates describe the general properties of a type.
-Synopsis:
-template <class T>
-struct alignment_of;
-
-template <class T>
-struct has_nothrow_assign;
-
-template <class T>
-struct has_nothrow_constructor;
-
-template <class T>
-struct has_nothrow_copy;
-
-template <class T>
-struct has_trivial_assign;
-
-template <class T>
-struct has_trivial_constructor;
-
-template <class T>
-struct has_trivial_copy;
-
-template <class T>
-struct has_trivial_destructor;
-
-template <class T>
-struct has_virtual_destructor;
-
-template <class T>
-struct is_abstract;
-
-template <class T>
-struct is_const;
-
-template <class T>
-struct is_empty;
-
-template <class T>
-struct is_stateless;
-
-template <class T>
-struct is_pod;
-
-template <class T>
-struct is_polymorphic;
-
-template <class T>
-struct is_volatile;
-
-template <class T, std::size_t N = 0>
-struct extent;
-
-template <class T>
-struct rank;
--These templates determine the whether there is a relationship -between two types:
-Synopsis:
-template <class Base, class Derived>
-struct is_base_of;
-
-template <class From, class To>
-struct is_convertible;
-
-template <class T, class U>
-struct is_same;
-
-The following templates transform one type to another,
-based upon some well-defined rule.
-Each template has a single member called type
that is the
-result of applying the transformation to the template argument T
.
Synopsis:
-template <class T>
-struct add_const;
-
-template <class T>
-struct add_cv;
-
-template <class T>
-struct add_pointer;
-
-template <class T>
-struct add_reference;
-
-template <class T>
-struct add_volatile;
-
-template <class T>
-struct remove_all_extents;
-
-template <class T>
-struct remove_const;
-
-template <class T>
-struct remove_cv;
-
-template <class T>
-struct remove_extent;
-
-template <class T>
-struct remove_pointer;
-
-template <class T>
-struct remove_reference;
-
-template <class T>
-struct remove_volatile;
--For all of these templates support for partial specialization of class templates is -required to correctly implement the transformation. -On the other hand, practice shows that many of the templates from this -category are very useful, and often essential for implementing some -generic libraries. Lack of these templates is often one of the major -limiting factors in porting those libraries to compilers that do not yet -support this language feature. As some of these compilers are going to be -around for a while, and at least one of them is very wide-spread, -it was decided that the library should provide workarounds where possible.
--The basic idea behind the workaround is to manually define full -specializations of all type transformation templates for all fundamental types, -and all their 1st and 2nd rank cv-[un]qualified derivative pointer types, and to -provide a user-level macro that will define all the explicit specializations needed -for any user-defined type T.
--The first part guarantees the successful compilation of something like this:
-BOOST_STATIC_ASSERT((is_same<char, remove_reference<char&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<char const, remove_reference<char const&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<char volatile, remove_reference<char volatile&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<char const volatile, remove_reference<char const volatile&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<char*, remove_reference<char*&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<char const*, remove_reference<char const*&>::type>::value));
-...
-BOOST_STATIC_ASSERT((is_same<char const volatile* const volatile* const volatile, remove_reference<char const volatile* const volatile* const volatile&>::type>::value));
-
-and the second part provides the library's users with a mechanism to make the
-above code work not only for char
, int
or other built-in type,
-but for they own types as well:
namespace myspace{
- struct MyClass {};
-}
-// declare this at global scope:
-BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(myspace::MyClass)
-// transformations on myspace::MyClass now work:
-BOOST_STATIC_ASSERT((is_same<myspace::MyClass, remove_reference<myspace::MyClass&>::type>::value));
-BOOST_STATIC_ASSERT((is_same<myspace::MyClass, remove_const<myspace::MyClass const>::type>::value));
-// etc.
-
--Note that the macro BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION evaluates -to nothing on those compilers that do support partial specialization.
-
-Some low level memory management routines need to synthesize a POD type with
-specific alignment properties. The template type_with_alignment
finds the smallest
-type with a specified alignment, while template aligned_storage
creates a type
-with a specific size and alignment.
Synopsis
-template <std::size_t Align>
-struct type_with_alignment;
-
-template <std::size_t Size, std::size_t Align>
-struct aligned_storage;
--The class template function_traits extracts information from function types -(see also is_function). This traits class allows you to tell how many arguments -a function takes, what those argument types are, and what the return type is.
-Synopsis
-template <std::size_t Align>
-struct function_traits;
-- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-This documentation was pulled together by John Maddock, using -Boost.Quickbook -and Boost.DocBook.
--The original version of this library was created by Steve Cleary, -Beman Dawes, Howard Hinnant, and John Maddock. John Maddock is the -current maintainer of the library.
--This version of type traits library is based on contributions by -Adobe Systems Inc, David Abrahams, Steve Cleary, -Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, -Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek.
--Mat Marcus and Jesse Jones invented, and -published a paper describing, -the partial specialization workarounds used in this library.
--Aleksey Gurtovoy added MPL integration to the library.
--The is_convertible template is based on code originally devised by -Andrei Alexandrescu, see -"Generic<Programming>: Mappings between Types and Values".
--The latest version of this library and documentation can be found at -www.boost.org. Bugs, suggestions and discussion -should be directed to boost@lists.boost.org -(see www.boost.org/more/mailing_lists.htm#main for subscription details).
-- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Demonstrates a version of std::copy
that uses has_trivial_assign
to
-determine whether to use memcpy
to optimise the copy operation
-(see copy_example.cpp):
//
-// opt::copy
-// same semantics as std::copy
-// calls memcpy where appropriate.
-//
-
-namespace detail{
-
-template<typename I1, typename I2, bool b>
-I2 copy_imp(I1 first, I1 last, I2 out, const boost::integral_constant<bool, b>&)
-{
- while(first != last)
- {
- *out = *first;
- ++out;
- ++first;
- }
- return out;
-}
-
-template<typename T>
-T* copy_imp(const T* first, const T* last, T* out, const boost::true_type&)
-{
- memcpy(out, first, (last-first)*sizeof(T));
- return out+(last-first);
-}
-
-
-}
-
-template<typename I1, typename I2>
-inline I2 copy(I1 first, I1 last, I2 out)
-{
- //
- // We can copy with memcpy if T has a trivial assignment operator,
- // and if the iterator arguments are actually pointers (this last
- // requirement we detect with overload resolution):
- //
- typedef typename std::iterator_traits<I1>::value_type value_type;
- return detail::copy_imp(first, last, out, boost::has_trivial_assign<value_type>());
-}
-
-Demonstrates a version of std::fill
that uses has_trivial_assign
to
-determine whether to use memset
to optimise the fill operation
-(see fill_example.cpp):
//
-// fill
-// same as std::fill, but uses memset where appropriate
-//
-namespace detail{
-
-template <typename I, typename T, bool b>
-void do_fill(I first, I last, const T& val, const boost::integral_constant<bool, b>&)
-{
- while(first != last)
- {
- *first = val;
- ++first;
- }
-}
-
-template <typename T>
-void do_fill(T* first, T* last, const T& val, const boost::true_type&)
-{
- std::memset(first, val, last-first);
-}
-
-}
-
-template <class I, class T>
-inline void fill(I first, I last, const T& val)
-{
- //
- // We can do an optimised fill if T has a trivial assignment
- // operator and if it's size is one:
- //
- typedef boost::integral_constant<bool,
- ::boost::has_trivial_assign<T>::value && (sizeof(T) == 1)> truth_type;
- detail::do_fill(first, last, val, truth_type());
-}
-
-Demonstrates a simple algorithm that uses __has_trivial_destruct
to
-determine whether to destructors need to be called
-(see trivial_destructor_example.cpp):
//
-// algorithm destroy_array:
-// The reverse of std::unitialized_copy, takes a block of
-// initialized memory and calls destructors on all objects therein.
-//
-
-namespace detail{
-
-template <class T>
-void do_destroy_array(T* first, T* last, const boost::false_type&)
-{
- while(first != last)
- {
- first->~T();
- ++first;
- }
-}
-
-template <class T>
-inline void do_destroy_array(T* first, T* last, const boost::true_type&)
-{
-}
-
-} // namespace detail
-
-template <class T>
-inline void destroy_array(T* p1, T* p2)
-{
- detail::do_destroy_array(p1, p2, ::boost::has_trivial_destructor<T>());
-}
-
-Demonstrates a version of std::iter_swap
that use type traits to
-determine whether an it's arguments are proxying iterators or not,
-if they're not then it just does a std::swap
of it's dereferenced
-arguments (the
-same as std::iter_swap
does), however if they are proxying iterators
-then takes special care over the swap to ensure that the algorithm
-works correctly for both proxying iterators, and even iterators of
-different types
-(see iter_swap_example.cpp):
//
-// iter_swap:
-// tests whether iterator is a proxying iterator or not, and
-// uses optimal form accordingly:
-//
-namespace detail{
-
-template <typename I>
-static void do_swap(I one, I two, const boost::false_type&)
-{
- typedef typename std::iterator_traits<I>::value_type v_t;
- v_t v = *one;
- *one = *two;
- *two = v;
-}
-template <typename I>
-static void do_swap(I one, I two, const boost::true_type&)
-{
- using std::swap;
- swap(*one, *two);
-}
-
-}
-
-template <typename I1, typename I2>
-inline void iter_swap(I1 one, I2 two)
-{
- //
- // See is both arguments are non-proxying iterators,
- // and if both iterator the same type:
- //
- typedef typename std::iterator_traits<I1>::reference r1_t;
- typedef typename std::iterator_traits<I2>::reference r2_t;
-
- typedef boost::integral_constant<bool,
- ::boost::is_reference<r1_t>::value
- && ::boost::is_reference<r2_t>::value
- && ::boost::is_same<r1_t, r2_t>::value> truth_type;
-
- detail::do_swap(one, two, truth_type());
-}
-- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-There are some traits that can not be implemented within the current C++ language: -to make these traits "just work" with user defined types, some kind of additional -help from the compiler is required. Currently (May 2005) MWCW 9 and Visual C++ 8 -provide the necessary intrinsics, and other compilers will no doubt follow in due -course.
--The Following traits classes always need compiler support to do the right thing -for all types -(but all have safe fallback positions if this support is unavailable):
--The following traits classes can't be portably implemented in the C++ language, -although in practice, the implementations do in fact do the right thing on all -the compilers we know about:
- --The following traits classes are dependent on one or more of the above:
--The hooks for compiler-intrinsic support are defined in -boost/type_traits/intrinsics.hpp, adding support for new compilers is simply -a matter of defining one of more of the following macros:
-BOOST_IS_UNION(T) | -Should evaluate to true if T is a union type | -
---|---|
BOOST_IS_POD(T) | -Should evaluate to true if T is a POD type | -
BOOST_IS_EMPTY(T) | -Should evaluate to true if T is an empty struct or union | -
BOOST_HAS_TRIVIAL_CONSTRUCTOR(T) | -Should evaluate to true if the default constructor for T is trivial (i.e. has no effect) | -
BOOST_HAS_TRIVIAL_COPY(T) | -Should evaluate to true if T has a trivial copy constructor (and can therefore be replaced by a call to memcpy) | -
BOOST_HAS_TRIVIAL_ASSIGN(T) | -Should evaluate to true if T has a trivial assignment operator (and can therefore be replaced by a call to memcpy) | -
BOOST_HAS_TRIVIAL_DESTRUCTOR(T) | -Should evaluate to true if T has a trivial destructor (i.e. ~T() has no effect) | -
BOOST_HAS_NOTHROW_CONSTRUCTOR(T) | -Should evaluate to true if T x; can not throw |
-
BOOST_HAS_NOTHROW_COPY(T) | -Should evaluate to true if T(t) can not throw |
-
BOOST_HAS_NOTHROW_ASSIGN(T) | -Should evaluate to true if T t, u; t = u can not throw |
-
BOOST_HAS_VIRTUAL_DESTRUCTOR(T) | -Should evaluate to true T has a virtual destructor | -
- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-All the value based traits in this library conform to MPL's requirements -for an Integral Constant type: that includes a number of rather intrusive -workarounds for broken compilers.
-
-Purely as an implementation detail, this
-means that true_type
inherits from boost::mpl::true_
, false_type
inherits
-from boost::mpl::false_
, and integral_constant<T, v>
inherits from
-boost::mpl::integral_c<T,v>
(provided T
is not bool
)
- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template <class T>
-struct add_const
-{
- typedef see-below
type;
-};
-type: The same type as T const
for all T
.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/add_const.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct add_cv
-{
- typedef see-below
type;
-};
-type: The same type as T const volatile
for all T
.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/add_cv.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct add_pointer
-{
- typedef see-below
type;
-};
-type: The same type as remove_reference<T>::type*
.
-The rationale for this template
-is that it produces the same type as TYPEOF(&t)
,
-where t
is an object of type T
.
C++ Standard Reference: 8.3.1.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/add_pointer.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct add_reference
-{
- typedef see-below
type;
-};
-type: If T
is not a reference type then T&
, otherwise T
.
C++ Standard Reference: 8.3.2.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/add_reference.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct add_volatile
-{
- typedef see-below
type;
-};
-type: The same type as T volatile
for all T
.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/add_volatile.hpp>
or #include <boost/type_traits.hpp>
template <std::size_t Align>
-struct aligned_storage
-{
- typedef see-below
type;
-};
-type: a built-in or POD type with an alignment
-that is a multiple of Align
.
Header: #include <boost/type_traits/aligned_storage.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct alignment_of : public integral_constant<std::size_t, ALIGNOF(T)> {};
-Inherits: Class template alignment_of inherits from
-integral_constant<std::size_t, ALIGNOF(T)>
, where ALIGNOF(T)
is the
-alignment of type T.
Note: strictly speaking you should only rely on
-the value of ALIGNOF(T)
being a multiple of the true alignment of T, although
-in practice it does compute the correct value in all the cases we know about.
Header: #include <boost/type_traits/alignment_of.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
alignment_of<int>
inherits fromintegral_constant<std::size_t, ALIGNOF(int)>
.
alignment_of<char>::type
is the typeintegral_constant<std::size_t, ALIGNOF(char)>
.
alignment_of<double>::value
is an integral constant -expression with valueALIGNOF(double)
.
alignment_of<T>::value_type
is the typestd::size_t
.
template <class T, std::size_t N = 0>
-struct extent : public integral_constant<std::size_t, EXTENT(T,N)> {};
-Inherits: Class template extent inherits from integral_constant<std::size_t, EXTENT(T,N)>
,
-where EXTENT(T,N)
is the number of elements in the N'th array dimention of type T
.
-If T
is not an array type, or if N > rank<T>::value
, or if the N'th array bound
-is incomplete, then EXTENT(T,N)
is zero.
Header: #include <boost/type_traits/extent.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
extent<int[1]>
inherits fromintegral_constant<std::size_t, 0>
.
extent<double[2][3][4], 1>::type
is the typeintegral_constant<std::size_t, 3>
.
extent<int[4]>::value
is an integral constant -expression that evaluates to 4.
extent<int[][2]>::value
is an integral constant -expression that evaluates to 0.
extent<int[][2], 1>::value
is an integral constant -expression that evaluates to 2.
extent<int*>::value
is an integral constant -expression that evaluates to 0.
extent<T>::value_type
is the typestd::size_t
.
template <class T>
-struct function_traits
-{
- static const std::size_t arity = see-below
;
- typedef see-below
result_type;
- typedef see-below
argN
_type;
-};
--The class template function_traits will only compile if:
-T
is a function type, note that this is not
-the same thing as a pointer to a function.
-Member | -Description | -
---|---|
function_traits<T>::arity |
-An integral constant expression that gives the number of arguments accepted by the function type F . |
-
function_traits<T>::result_type |
-The type returned by function type F . |
-
function_traits<T>::arg |
-The N th argument type of function type F , where 1 <= N <= arity of F . |
-
Expression | -Result | -
---|---|
function_traits<void (void)>::arity |
-An integral constant expression that has the value 0. | -
function_traits<long (int)>::arity |
-An integral constant expression that has the value 1. | -
function_traits<long (int, long, double, void*)>::arity |
-An integral constant expression that has the value 4. | -
function_traits<void (void)>::result_type |
-The type void . |
-
function_traits<long (int)>::result_type |
-The type long . |
-
function_traits<long (int)>::arg0_type |
-The type int . |
-
function_traits<long (int, long, double, void*)>::arg3_type |
-The type void* . |
-
function_traits<long (int, long, double, void*)>::arg4_type |
-A compiler error: there is no arg4_type since there are only three arguments. |
-
function_traits<long (*)(void)>::arity |
-A compiler error: argument type is a function pointer, and not a function type. | -
template <class T>
-struct has_nothrow_assign : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a non-throwing assignment-operator
-then inherits from true_type, otherwise inherits from false_type. Type T
-must be a complete type.
Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
-
-Without some (as yet unspecified) help from the compiler,
-has_nothrow_assign
will never report that a class or struct has a
-non-throwing assignment-operator; this is always safe, if possibly sub-optimal.
-Currently (May 2005) only Visual C++ 8 has the necessary compiler support to ensure that this
-trait "just works".
Header: #include <boost/type_traits/has_nothrow_assign.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct has_nothrow_constructor : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a non-throwing default-constructor
-then inherits from true_type, otherwise inherits from false_type. Type T
-must be a complete type.
Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
-
-Without some (as yet unspecified) help from the compiler,
-has_nothrow_constructor
will never report that a class or struct has a
-non-throwing default-constructor; this is always safe, if possibly sub-optimal.
-Currently (May 2005) only Visual C++ 8 has the necessary compiler intrinsics to ensure that this
-trait "just works".
Header: #include <boost/type_traits/has_nothrow_constructor.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct has_nothrow_copy : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a non-throwing copy-constructor
-then inherits from true_type, otherwise inherits from false_type. Type T
-must be a complete type.
Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
-
-Without some (as yet unspecified) help from the compiler,
-has_nothrow_copy
will never report that a class or struct has a
-non-throwing copy-constructor; this is always safe, if possibly sub-optimal.
-Currently (May 2005) only Visual C++ 8 has the necessary compiler intrinsics to ensure that this
-trait "just works".
Header: #include <boost/type_traits/has_nothrow_copy.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct has_trivial_assign : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a trivial assignment-operator -then inherits from true_type, otherwise inherits from false_type.
-
-If a type has a trivial assignment-operator then the operator has the same effect
-as copying the bits of one object to the other:
-calls to the operator can be safely replaced with a call to memcpy
.
Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, -has_trivial_assign will never report that a user-defined class or struct has a -trivial constructor; this is always safe, if possibly sub-optimal. Currently -(May 2005) only MWCW 9 and Visual C++ 8 have the necessary compiler intrinsics to detect -user-defined classes with trivial constructors.
-C++ Standard Reference: 12.8p11.
-Header: #include <boost/type_traits/has_trivial_assign.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
has_trivial_assign<int>
inherits fromtrue_type
.
has_trivial_assign<char*>::type
is the typetrue_type
.
has_trivial_assign<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
has_trivial_assign<MyClass>::value
is an integral constant -expression that evaluates to false.
has_trivial_assign<T>::value_type
is the typebool
.
template <class T>
-struct has_trivial_constructor : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a trivial default-constructor -then inherits from true_type, otherwise inherits from false_type.
--If a type has a trivial default-constructor then the constructor have no effect: -calls to the constructor can be safely omitted. Note that using meta-programming -to omit a call to a single trivial-constructor call is of no benefit whatsoever. -However, if loops and/or exception handling code can also be omitted, then some -benefit in terms of code size and speed can be obtained.
-Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, -has_trivial_constructor will never report that a user-defined class or struct has a -trivial constructor; this is always safe, if possibly sub-optimal. Currently -(May 2005) only MWCW 9 and Visual C++ 8 have the necessary compiler intrinsics to detect -user-defined classes with trivial constructors.
-C++ Standard Reference: 12.1p6.
-Header: #include <boost/type_traits/has_trivial_constructor.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
has_trivial_constructor<int>
inherits fromtrue_type
.
has_trivial_constructor<char*>::type
is the typetrue_type
.
has_trivial_constructor<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
has_trivial_constructor<MyClass>::value
is an integral constant -expression that evaluates to false.
has_trivial_constructor<T>::value_type
is the typebool
.
template <class T>
-struct has_trivial_copy : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a trivial copy-constructor -then inherits from true_type, otherwise inherits from false_type.
-
-If a type has a trivial copy-constructor then the constructor has the same effect
-as copying the bits of one object to the other:
-calls to the constructor can be safely replaced with a call to memcpy
.
Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, -has_trivial_copy will never report that a user-defined class or struct has a -trivial constructor; this is always safe, if possibly sub-optimal. Currently -(May 2005) only MWCW 9 and Visual C++ 8 have the necessary compiler intrinsics to detect -user-defined classes with trivial constructors.
-C++ Standard Reference: 12.8p6.
-Header: #include <boost/type_traits/has_trivial_copy.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
has_trivial_copy<int>
inherits fromtrue_type
.
has_trivial_copy<char*>::type
is the typetrue_type
.
has_trivial_copy<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
has_trivial_copy<MyClass>::value
is an integral constant -expression that evaluates to false.
has_trivial_copy<T>::value_type
is the typebool
.
template <class T>
-struct has_trivial_destructor : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a trivial destructor -then inherits from true_type, otherwise inherits from false_type.
--If a type has a trivial destructor then the destructor has no effect: -calls to the destructor can be safely omitted. Note that using meta-programming -to omit a call to a single trivial-constructor call is of no benefit whatsoever. -However, if loops and/or exception handling code can also be omitted, then some -benefit in terms of code size and speed can be obtained.
-Compiler Compatibility: If the compiler does not support partial-specialization of class -templates, then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, -has_trivial_destructor will never report that a user-defined class or struct has a -trivial destructor; this is always safe, if possibly sub-optimal. Currently -(May 2005) only MWCW 9 and Visual C++ 8 have the necessary compiler intrinsics to detect -user-defined classes with trivial constructors.
-C++ Standard Reference: 12.4p3.
-Header: #include <boost/type_traits/has_trivial_destructor.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
has_trivial_destructor<int>
inherits fromtrue_type
.
has_trivial_destructor<char*>::type
is the typetrue_type
.
has_trivial_destructor<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
has_trivial_destructor<MyClass>::value
is an integral constant -expression that evaluates to false.
has_trivial_destructor<T>::value_type
is the typebool
.
template <class T>
-struct has_virtual_destructor : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) type with a virtual destructor -then inherits from true_type, otherwise inherits from false_type.
-Compiler Compatibility: This trait is provided for completeness, since it's part of the -Technical Report on C++ Library Extensions. However, there is currently no -way to portably implement this trait. The default version provided -always inherits from false_type, and has to be explicitly specialized for -types with virtual destructors unless the compiler used has compiler intrinsics -that enable the trait to do the right thing: currently (May 2005) only Visual C++ -8 has the necessary intrinsics.
-C++ Standard Reference: 12.4.
-Header: #include <boost/type_traits/has_virtual_destructor.hpp>
or #include <boost/type_traits.hpp>
template <class T, T val>
-struct integral_constant
-{
- typedef integral_constant<T, val> type;
- typedef T value_type;
- static const T value = val;
-};
-
-typedef integral_constant<bool, true> true_type;
-typedef integral_constant<bool, false> false_type;
-
-Class template integral_constant
is the common base class for all the value-based
-type traits. The two typedef's true_type
and false_type
are provided for
-convenience: most of the value traits are Boolean properties and so will inherit from
-one of these.
template <class T>
-struct is_abstract : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) abstract type then inherits from -true_type, otherwise inherits from false_type.
-C++ Standard Reference: 10.3.
-Header: #include <boost/type_traits/is_abstract.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: The compiler must support DR337 (as of April 2005: GCC 3.4, VC++ 7.1 (and later), - Intel C++ 7 (and later), and Comeau 4.3.2). -Otherwise behaves the same as is_polymorphic; -this is the "safe fallback position" for which polymorphic types are always -regarded as potentially abstract. The macro BOOST_NO_IS_ABSTRACT is used to -signify that the implementation is buggy, users should check for this in their -own code if the "safe fallback" is not suitable for their particular use-case.
-Examples:
-Given:
class abc{ virtual ~abc() = 0; };
is_abstract<abc>
inherits fromtrue_type
.
is_abstract<abc>::type
is the typetrue_type
.
is_abstract<abc const>::value
is an integral constant -expression that evaluates to true.
is_abstract<T>::value_type
is the typebool
.
template <class T>
-struct is_arithmetic : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) arithmetic type then inherits from -true_type, otherwise inherits from false_type. Arithmetic types include -integral and floating point types (see also is_integral and is_floating_point).
-C++ Standard Reference: 3.9.1p8.
-Header: #include <boost/type_traits/is_arithmetic.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_arithmetic<int>
inherits fromtrue_type
.
is_arithmetic<char>::type
is the typetrue_type
.
is_arithmetic<double>::value
is an integral constant -expression that evaluates to true.
is_arithmetic<T>::value_type
is the typebool
.
template <class T>
-struct is_array : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) array type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 8.3.4.
-Header: #include <boost/type_traits/is_array.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: If the compiler does not support -partial-specialization of class templates, then this template -can give the wrong result with function types.
-Examples:
-
is_array<int[2]>
inherits fromtrue_type
.
is_array<char[2][3]>::type
is the typetrue_type
.
is_array<double[]>::value
is an integral constant -expression that evaluates to true.
is_array<T>::value_type
is the typebool
.
template <class Base, class Derived>
-struct is_base_of : public true_type-or-false_type
{};
-Inherits: If Base is base class of type Derived then inherits from true_type, -otherwise inherits from false_type.
--This template will detect non-public base classes, and ambiguous base classes.
-
-Note that a class is not considered to be it's own base class,
-likewise, if either Base
or Derived
are non-class types,
-then the class will always inherit from false_type.
-Types Base
and Derived
must not be incomplete types.
C++ Standard Reference: 10.
-Header: #include <boost/type_traits/is_base_of.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: If the compiler does not support partial-specialization of class templates,
-then this template can not be used with function types. There are some older compilers
-which will produce compiler errors if Base
is a private base class of Derived
, or if
-Base
is an ambiguous base of Derived
. These compilers include Borland C++, older
-versions of Sun Forte C++, Digital Mars C++, and older versions of EDG based compilers.
Examples:
-Given:
class Base{}; class Derived : public Base{};
is_base_of<Base, Derived>
inherits fromtrue_type
.
is_base_of<Base, Derived>::type
is the typetrue_type
.
is_base_of<Base, Derived>::value
is an integral constant -expression that evaluates to true.
is_base_of<Base, Base>::value
is an integral constant -expression that evaluates to false: a class is not it's own base.
is_base_of<Derived, Base>::value
is an integral constant -expression that evaluates to false: the arguments are the wrong way round.
is_base_of<T>::value_type
is the typebool
.
template <class T>
-struct is_class : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) class type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 9.2.
-Header: #include <boost/type_traits/is_class.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: Without (some as yet unspecified) help from the compiler, -we cannot distinguish between union and class types, as a result this type -will erroneously inherit from true_type for union types. See also is_union. -Currently (May 2005) only Visual C++ 8 has the necessary compiler intrinsics to -correctly identify union types, and therefore make is_class function correctly.
-Examples:
-Given:
class MyClass;
then:
is_class<MyClass>
inherits fromtrue_type
.
is_class<MyClass const>::type
is the typetrue_type
.
is_class<MyClass>::value
is an integral constant -expression that evaluates to true.
is_class<MyClass&>::value
is an integral constant -expression that evaluates to false.
is_class<MyClass*>::value
is an integral constant -expression that evaluates to false.
is_class<T>::value_type
is the typebool
.
template <class T>
-struct is_compound : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) compound type then inherits from true_type, -otherwise inherits from false_type. Any type that is not a fundamental type is -a compound type (see also is_fundamental).
-C++ Standard Reference: 3.9.2.
-Header: #include <boost/type_traits/is_compound.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_compound<MyClass>
inherits fromtrue_type
.
is_compound<MyEnum>::type
is the typetrue_type
.
is_compound<int*>::value
is an integral constant -expression that evaluates to true.
is_compound<int&>::value
is an integral constant -expression that evaluates to true.
is_compound<int>::value
is an integral constant -expression that evaluates to false.
is_compound<T>::value_type
is the typebool
.
template <class T>
-struct is_const : public true_type-or-false_type
{};
-Inherits: If T is a (top level) const-qualified type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.3.
-Header: #include <boost/type_traits/is_const.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_const<int const>
inherits fromtrue_type
.
is_const<int const volatile>::type
is the typetrue_type
.
is_const<int* const>::value
is an integral constant -expression that evaluates to true.
is_const<int const*>::value
is an integral constant -expression that evaluates to false: the const-qualifier is not -at the top level in this case.
is_const<int const&>::value
is an integral constant -expression that evaluates to false: the const-qualifier is not -at the top level in this case.
is_const<int>::value
is an integral constant -expression that evaluates to false.
is_const<T>::value_type
is the typebool
.
template <class From, class To>
-struct is_convertible : public true_type-or-false_type
{};
-Inherits: If an imaginary lvalue of type From
is convertible to type To
then
-inherits from true_type, otherwise inherits from false_type.
-Type From must not be an incomplete type.
--Type To must not be an incomplete, or function type.
--No types are considered to be convertible to array types or abstract-class types.
-
-This template can not detect whether a converting-constructor is public
or not: if
-type To
has a private
converting constructor from type From
then instantiating
-is_convertible<From, To>
will produce a compiler error. For this reason is_convertible
-can not be used to determine whether a type has a public
copy-constructor or not.
-This template will also produce compiler errors if the conversion is ambiguous, -for example:
-struct A {};
-struct B : A {};
-struct C : A {};
-struct D : B, C {};
-// This produces a compiler error, the conversion is ambiguous:
-bool const y = boost::is_convertible<D*,A*>::value;
-C++ Standard Reference: 4 and 8.5.
-Compiler Compatibility: This template is currently broken with Borland C++ Builder 5 (and earlier),
-for constructor-based conversions, and for the Metrowerks 7 (and earlier)
-compiler in all cases. If the compiler does not support is_abstract
, then the
-template parameter To
must not be an abstract type.
Header: #include <boost/type_traits/is_convertible.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_convertible<int, double>
inherits fromtrue_type
.
is_convertible<const int, double>::type
is the typetrue_type
.
is_convertible<int* const, int*>::value
is an integral constant -expression that evaluates to true.
is_convertible<int const*, int*>::value
is an integral constant -expression that evaluates to false: the conversion would require aconst_cast
.
is_convertible<int const&, long>::value
is an integral constant -expression that evaluates to true.
is_convertible<int>::value
is an integral constant -expression that evaluates to false.
is_convertible<T>::value_type
is the typebool
.
template <class T>
-struct is_empty : public true_type-or-false_type
{};
-Inherits: If T is an empty class type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 10p5.
-Header: #include <boost/type_traits/is_empty.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: In order to correctly detect empty classes this trait relies on either:
--Can not be used with incomplete types.
--Can not be used with union types, until is_union can be made to work.
--If the compiler does not support partial-specialization of class templates, -then this template can not be used with abstract types.
-Examples:
-Given:
struct empty_class {};
is_empty<empty_class>
inherits fromtrue_type
.
is_empty<empty_class const>::type
is the typetrue_type
.
is_empty<empty_class>::value
is an integral constant -expression that evaluates to true.
is_empty<T>::value_type
is the typebool
.
template <class T>
-struct is_enum : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) enum type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 7.2.
-Header: #include <boost/type_traits/is_enum.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: Requires a correctly functioning is_convertible template; - this means that is_enum is currently broken under Borland C++ Builder 5, - and for the Metrowerks compiler prior to version 8, other compilers - should handle this template just fine.
-Examples:
-Given:
enum my_enum { one, two };
is_enum<my_enum>
inherits fromtrue_type
.
is_enum<my_enum const>::type
is the typetrue_type
.
is_enum<my_enum>::value
is an integral constant -expression that evaluates to true.
is_enum<my_enum&>::value
is an integral constant -expression that evaluates to false.
is_enum<my_enum*>::value
is an integral constant -expression that evaluates to false.
is_enum<T>::value_type
is the typebool
.
template <class T>
-struct is_floating_point : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) floating point type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.1p8.
-Header: #include <boost/type_traits/is_floating_point.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_floating_point<float>
inherits fromtrue_type
.
is_floating_point<double>::type
is the typetrue_type
.
is_floating_point<long double>::value
is an integral constant -expression that evaluates to true.
is_floating_point<T>::value_type
is the typebool
.
template <class T>
-struct is_function : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) function type then inherits from true_type, -otherwise inherits from false_type. Note that this template does not detect /pointers -to functions, or /references to functions, these are detected by is_pointer and -is_reference respectively:
-typedef int f1(); // f1 is of function type.
-typedef int (f2*)(); // f2 is a pointer to a function.
-typedef int (f3&)(); // f3 is a reference to a function.
-
-C++ Standard Reference: 3.9.2p1 and 8.3.5.
-Header: #include <boost/type_traits/is_function.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_function<int (void)>
inherits fromtrue_type
.
is_function<long (double, int)>::type
is the typetrue_type
.
is_function<long (double, int)>::value
is an integral constant -expression that evaluates to true.
is_function<long (*)(double, int)>::value
is an integral constant -expression that evaluates to false: the argument in this case is a pointer type, -not a function type.
is_function<long (&)(double, int)>::value
is an integral constant -expression that evaluates to false: the argument in this case is a -reference to a function, not a function type.
is_function<long (MyClass::*)(double, int)>::value
is an integral constant -expression that evaluates to false: the argument in this case is a pointer -to a member function.
is_function<T>::value_type
is the typebool
.
template <class T>
-struct is_fundamental : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) fundamental type then inherits from true_type, -otherwise inherits from false_type. Fundamental types include integral, floating -point and void types (see also is_integral, is_floating_point and is_void)
-C++ Standard Reference: 3.9.1.
-Header: #include <boost/type_traits/is_fundamental.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_fundamental<int)>
inherits fromtrue_type
.
is_fundamental<double const>::type
is the typetrue_type
.
is_fundamental<void>::value
is an integral constant -expression that evaluates to true.
is_fundamental<T>::value_type
is the typebool
.
template <class T>
-struct is_integral : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) integral type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.1p7.
-Header: #include <boost/type_traits/is_integral.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_integral<int>
inherits fromtrue_type
.
is_integral<const char>::type
is the typetrue_type
.
is_integral<long>::value
is an integral constant -expression that evaluates to true.
is_integral<T>::value_type
is the typebool
.
template <class T>
-struct is_member_function_pointer : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) pointer to a member function -then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 8.3.3.
-Header: #include <boost/type_traits/is_member_function_pointer.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_member_function_pointer<int (MyClass::*)(void)>
inherits fromtrue_type
.
is_member_function_pointer<int (MyClass::*)(char)>::type
is the typetrue_type
.
is_member_function_pointer<int (MyClass::*)(void)const>::value
is an integral constant -expression that evaluates to true.
is_member_function_pointer<int (MyClass::*)>::value
is an integral constant -expression that evaluates to false: the argument in this case is a pointer to -a data member and not a member function, see is_member_object_pointer -and is_member_pointer
is_member_function_pointer<T>::value_type
is the typebool
.
template <class T>
-struct is_member_object_pointer : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) pointer to a member object (a data member) -then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 8.3.3.
-Header: #include <boost/type_traits/is_member_object_pointer.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_member_object_pointer<int (MyClass::*)>
inherits fromtrue_type
.
is_member_object_pointer<double (MyClass::*)>::type
is the typetrue_type
.
is_member_object_pointer<const int (MyClass::*)>::value
is an integral constant -expression that evaluates to true.
is_member_object_pointer<int (MyClass::*)(void)>::value
is an integral constant -expression that evaluates to false: the argument in this case is a pointer to -a member function and not a member object, see is_member_function_pointer -and is_member_pointer
is_member_object_pointer<T>::value_type
is the typebool
.
template <class T>
-struct is_member_pointer : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) pointer to a member (either a function -or a data member) -then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 8.3.3.
-Header: #include <boost/type_traits/is_member_pointer.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_member_pointer<int (MyClass::*)>
inherits fromtrue_type
.
is_member_pointer<int (MyClass::*)(char)>::type
is the typetrue_type
.
is_member_pointer<int (MyClass::*)(void)const>::value
is an integral constant -expression that evaluates to true.
is_member_pointer<T>::value_type
is the typebool
.
template <class T>
-struct is_object : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) object type -then inherits from true_type, -otherwise inherits from false_type. All types are object types except -references, void, and function types.
-C++ Standard Reference: 3.9p9.
-Header: #include <boost/type_traits/is_object.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_object<int>
inherits fromtrue_type
.
is_object<int*>::type
is the typetrue_type
.
is_object<int (*)(void)>::value
is an integral constant -expression that evaluates to true.
is_object<int (MyClass::*)(void)const>::value
is an integral constant -expression that evaluates to true.
is_object<int &>::value
is an integral constant -expression that evaluates to false: reference types are not objects
is_object<int (double)>::value
is an integral constant -expression that evaluates to false: function types are not objects
is_object<const void>::value
is an integral constant -expression that evaluates to false: void is not an object type
is_object<T>::value_type
is the typebool
.
template <class T>
-struct is_pod : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) POD type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9p10 and 9p4.
-Compiler Compatibility: If the compiler does not support partial-specialization -of class templates, then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, is_pod will -never report that a class or struct is a POD; this is always safe, -if possibly sub-optimal. Currently (May 2005) only MWCW 9 and Visual C++ 8 have the -necessary compiler-intrinsics.
-Header: #include <boost/type_traits/is_pod.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_pod<int>
inherits fromtrue_type
.
is_pod<char*>::type
is the typetrue_type
.
is_pod<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
is_pod<MyClass>::value
is an integral constant -expression that evaluates to false.
is_pod<T>::value_type
is the typebool
.
template <class T>
-struct is_pointer : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) pointer type (includes function pointers, -but excludes pointers to members) then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2p2 and 8.3.1.
-Header: #include <boost/type_traits/is_pointer.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_pointer<int*>
inherits fromtrue_type
.
is_pointer<char* const>::type
is the typetrue_type
.
is_pointer<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
is_pointer<int (MyClass::*)(long)>::value
is an integral constant -expression that evaluates to false.
is_pointer<int (MyClass::*)>::value
is an integral constant -expression that evaluates to false.
is_pointer<T>::value_type
is the typebool
.
template <class T>
-struct is_polymorphic : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) polymorphic type
-then inherits from true_type,
-otherwise inherits from false_type. Type T
must be a complete type.
C++ Standard Reference: 10.3.
-Compiler Compatibility: The implementation requires some knowledge of the compilers ABI, -it does actually seem to work with the majority of compilers though.
-Header: #include <boost/type_traits/is_polymorphic.hpp>
or #include <boost/type_traits.hpp>
Examples:
-Given:
class poly{ virtual ~poly(); };
is_polymorphic<poly>
inherits fromtrue_type
.
is_polymorphic<poly const>::type
is the typetrue_type
.
is_polymorphic<poly>::value
is an integral constant -expression that evaluates to true.
is_polymorphic<T>::value_type
is the typebool
.
template <class T, class U>
-struct is_same : public true_type-or-false_type
{};
-Inherits: If T and U are the same types then inherits from -true_type, otherwise inherits from false_type.
-Header: #include <boost/type_traits/is_same.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: If the compiler does not support partial-specialization of class templates, -then this template can not be used with abstract, incomplete or function types.
-Examples:
-
is_same<int, int>
inherits fromtrue_type
.
is_same<int, int>::type
is the typetrue_type
.
is_same<int, int>::value
is an integral constant -expression that evaluates to true.
is_same<int const, int>::value
is an integral constant -expression that evaluates to false.
is_same<int&, int>::value
is an integral constant -expression that evaluates to false.
is_same<T>::value_type
is the typebool
.
template <class T>
-struct is_scalar : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) scalar type then inherits from -true_type, otherwise inherits from false_type. Scalar types include -integral, floating point, enumeration, pointer, and pointer-to-member types.
-C++ Standard Reference: 3.9p10.
-Header: #include <boost/type_traits/is_scalar.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: If the compiler does not support partial-specialization of class templates, -then this template can not be used with function types.
-Examples:
-
is_scalar<int*>
inherits fromtrue_type
.
is_scalar<int>::type
is the typetrue_type
.
is_scalar<double>::value
is an integral constant -expression that evaluates to true.
is_scalar<int (*)(long)>::value
is an integral constant -expression that evaluates to true.
is_scalar<int (MyClass::*)(long)>::value
is an integral constant -expression that evaluates to true.
is_scalar<int (MyClass::*)>::value
is an integral constant -expression that evaluates to true.
is_scalar<T>::value_type
is the typebool
.
template <class T>
-struct is_stateless : public true_type-or-false_type
{};
-Inherits: Ff T is a stateless type then inherits from true_type, otherwise -from false_type.
--Type T must be a complete type.
-
-A stateless type is a type that has no storage and whose constructors and
-destructors are trivial. That means that is_stateless
only inherits from
-true_type if the following expression is true
:
::boost::has_trivial_constructor<T>::value
-&& ::boost::has_trivial_copy<T>::value
-&& ::boost::has_trivial_destructor<T>::value
-&& ::boost::is_class<T>::value
-&& ::boost::is_empty<T>::value
-C++ Standard Reference: 3.9p10.
-Header: #include <boost/type_traits/is_stateless.hpp>
or #include <boost/type_traits.hpp>
Compiler Compatibility: If the compiler does not support partial-specialization of class templates, -then this template can not be used with function types.
--Without some (as yet unspecified) help from the compiler, is_stateless will never -report that a class or struct is stateless; this is always safe, -if possibly sub-optimal. Currently (May 2005) only MWCW 9 and Visual C++ 8 have the necessary -compiler intrinsics to make this template work automatically.
-template <class T>
-struct is_reference : public true_type-or-false_type
{};
-Inherits: If T is a reference pointer type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.2 and 8.3.2.
-Compiler Compatibility: If the compiler does not -support partial-specialization of class templates, -then this template may report the wrong result for function types, -and for types that are both const and volatile qualified.
-Header: #include <boost/type_traits/is_reference.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_reference<int&>
inherits fromtrue_type
.
is_reference<int const&>::type
is the typetrue_type
.
is_reference<int (&)(long)>::value
is an integral constant -expression that evaluates to true (the argument in this case is -a reference to a function).
is_reference<T>::value_type
is the typebool
.
template <class T>
-struct is_union : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) union type then inherits from true_type, -otherwise inherits from false_type. Currently requires some kind of compiler -support, otherwise unions are identified as classes.
-C++ Standard Reference: 3.9.2 and 9.5.
-Compiler Compatibility: Without (some as yet unspecified) help from the -compiler, we cannot distinguish between union and class types using only standard C++, -as a result this type will never inherit from true_type, unless the user explicitly -specializes the template for their user-defined union types, or unless the compiler -supplies some unspecified intrinsic that implements this functionality. Currently -(May 2005) only Visual C++ 8 has the necessary compiler intrinsics to make this -trait "just work" without user intervention.
-Header: #include <boost/type_traits/is_union.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_union<void>
inherits fromtrue_type
.
is_union<const void>::type
is the typetrue_type
.
is_union<void>::value
is an integral constant -expression that evaluates to true.
is_union<void*>::value
is an integral constant -expression that evaluates to false.
is_union<T>::value_type
is the typebool
.
template <class T>
-struct is_void : public true_type-or-false_type
{};
-Inherits: If T is a (possibly cv-qualified) void type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.1p9.
-Header: #include <boost/type_traits/is_void.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_void<void>
inherits fromtrue_type
.
is_void<const void>::type
is the typetrue_type
.
is_void<void>::value
is an integral constant -expression that evaluates to true.
is_void<void*>::value
is an integral constant -expression that evaluates to false.
is_void<T>::value_type
is the typebool
.
template <class T>
-struct is_volatile : public true_type-or-false_type
{};
-Inherits: If T is a (top level) volatile-qualified type then inherits from true_type, -otherwise inherits from false_type.
-C++ Standard Reference: 3.9.3.
-Header: #include <boost/type_traits/is_volatile.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
is_volatile<volatile int>
inherits fromtrue_type
.
is_volatile<const volatile int>::type
is the typetrue_type
.
is_volatile<int* volatile>::value
is an integral constant -expression that evaluates to true.
is_volatile<int volatile*>::value
is an integral constant -expression that evaluates to false: the volatile qualifier is not -at the top level in this case.
is_volatile<T>::value_type
is the typebool
.
template <class T>
-struct rank : public integral_constant<std::size_t, RANK(T)> {};
-Inherits: Class template rank inherits from integral_constant<std::size_t, RANK(T)>
,
-where RANK(T)
is the number of array dimensions in type T
.
-If T
is not an array type, then RANK(T)
is zero.
Header: #include <boost/type_traits/rank.hpp>
or #include <boost/type_traits.hpp>
Examples:
-
rank<int[]>
inherits fromintegral_constant<std::size_t, 1>
.
rank<double[2][3][4]>::type
is the typeintegral_constant<std::size_t, 3>
.
rank<int[1]>::value
is an integral constant -expression that evaluates to 1.
rank<int[][2]>::value
is an integral constant -expression that evaluates to 2.
rank<int*>::value
is an integral constant -expression that evaluates to 0.
rank<T>::value_type
is the typestd::size_t
.
template <class T>
-struct remove_all_extents
-{
- typedef see-below
type;
-};
-type: If T
is an array type, then removes all of the array bounds on T
, otherwise
-leaves T
unchanged.
C++ Standard Reference: 8.3.4.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_all_extents.hpp>
or #include <boost/type_traits.hpp>
Expression | -Result Type | -
---|---|
remove_all_extents<int>::type |
-int |
-
remove_all_extents<int const[2]>::type |
-int const |
-
remove_all_extents<int[][2]>::type |
-int |
-
remove_all_extents<int[2][3][4]>::type |
-int |
-
remove_all_extents<int const*>::type |
-int const* |
-
template <class T>
-struct remove_const
-{
- typedef see-below
type;
-};
-type: The same type as T
, but with any top level const-qualifier removed.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_const.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct remove_cv
-{
- typedef see-below
type;
-};
-type: The same type as T
, but with any top level cv-qualifiers removed.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_cv.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct remove_extent
-{
- typedef see-below
type;
-};
-type: If T
is an array type, then removes the topmost array bound,
-otherwise leaves T
unchanged.
C++ Standard Reference: 8.3.4.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_extent.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct remove_pointer
-{
- typedef see-below
type;
-};
-type: The same type as T
, but with any pointer modifier removed.
C++ Standard Reference: 8.3.1.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_pointer.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct remove_reference
-{
- typedef see-below
type;
-};
-type: The same type as T
, but with any reference modifier removed.
C++ Standard Reference: 8.3.2.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_reference.hpp>
or #include <boost/type_traits.hpp>
template <class T>
-struct remove_volatile
-{
- typedef see-below
type;
-};
-type: The same type as T
, but with any top level volatile-qualifier removed.
C++ Standard Reference: 3.9.3.
-Compiler Compatibility: If the compiler does not support partial specialization of class-templates
-then this template will compile, but the member type
will always be the same as
-type T
except where compiler workarounds have been applied.
Header: #include <boost/type_traits/remove_volatile.hpp>
or #include <boost/type_traits.hpp>
Expression | -Result Type | -
---|---|
remove_volatile<int>::type |
-int |
-
remove_volatile<int volatile>::type |
-int |
-
remove_volatile<int const volatile>::type |
-int const |
-
remove_volatile<int volatile&>::type |
-int const& |
-
remove_volatile<int volatile*>::type |
-int const* |
-
template <std::size_t Size, std::size_t Align>
-struct type_with_alignment
-{
- typedef see-below
type;
-};
-type: a built-in or POD type with size Size
and an alignment
-that is a multiple of Align
.
Header: #include <boost/type_traits/type_with_alignment.hpp>
or #include <boost/type_traits.hpp>
- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Occationally the end user may need to provide their own specialization -for one of the type traits - typically where intrinsic compiler support -is required to implement a specific trait fully. -These specializations should derive from boost::true_type or boost::false_type -as appropriate:
-#include <boost/type_traits/is_pod.hpp>
-#include <boost/type_traits/is_class.hpp>
-#include <boost/type_traits/is_union.hpp>
-
-struct my_pod{};
-struct my_union
-{
- char c;
- int i;
-};
-
-namespace boost
-{
- template<>
- struct is_pod<my_pod> : public true_type{};
-
- template<>
- struct is_pod<my_union> : public true_type{};
-
- template<>
- struct is_union<my_union> : public true_type{};
-
- template<>
- struct is_class<my_union> : public false_type{};
-}
-- | Copyright © 2000, 2005 Adobe Systems Inc, David Abrahams, Steve Cleary, - Beman Dawes, Aleksey Gurtovoy, Howard Hinnant, Jesse Jones, Mat Marcus, - Itay Maman, John Maddock, Thorsten Ottosen, Robert Ramey and Jeremy Siek | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2003-2005 Douglas Gregor
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.
-Table of Contents
- -Last revised: January 24, 2005 at 02:13:05 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -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.
-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 18.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$"> - <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
dirname
boost/libs
, in which the library
- resides. This name may be a relative path, such as
- math/octonion
, using "/" for the directory
- separator.id
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
$Date$
, 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 Chapter 17, Getting Started.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 18.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 18.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 18.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 |
-
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boostbook
boostbook — Defines a BoostBook book
-This element is the topmost level defined by
- boost.xml
for all Boost documentation. It will
- not generally be used by developers.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
class-specialization
class-specialization — A specialization (partial or full) of a class template
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
class
class — Declares a class or class template
-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.
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
code
code — Mimics the code
tag in HTML
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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
compile-fail-test
compile-fail-test — A testcase that should fail to compile
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
compile-test
compile-test — A testcase that should compile correctly
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
complexity
complexity — The time/space/etc. complexity of a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
constructor
constructor — Declares a constructor of the enclosing class
-General documentation on functions in BoostBook is provided in
- the function
- element documentation.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
copy-assignment
copy-assignment — Declares a copy-assignment operator
-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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
data-member
data-member — Declares a data member of a class
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
default
default — The default value of a function or template parameter
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
description
description — Detailed description of a construct
-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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
destructor
destructor — Declares a destructor for the enclosing class
-General documentation on functions in BoostBook is provided in
- the function
- element documentation.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
effects
effects — Declares the side effects of a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
enum
enum — Declares an enumeration type
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
enumvalue
enumvalue — A single value of an enumeration
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
free-function-group
free-function-group — A set of functions that are grouped together under one name
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
function
function — Declares a function
-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>&</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>-
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
functionname
functionname — References a function with the given name
-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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
header
header — Declares a C++ header with the given name
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
if-fails
if-fails — What it means when a testcase fails
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
inherit
inherit — Declares a base class of the enclosing class or struct
-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).
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
library-reference
library-reference — Declares the reference material for a library
-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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
library
library — Top-level element for a library
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -- |
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
librarycategory
librarycategory — Declares that the enclosing library is in this category
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
librarycategorydef
librarycategorydef — Defines a new library category
-All library category definitions should be in doc/src/boost.xml
, and the names of categories must be prefixed with "category:
".
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
librarycategorylist
librarycategorylist — Categorized listing of libraries
-This element is not intended for use by developers, but is
- used by doc/src/boost.xml
as a
- placeholder.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
libraryinfo
libraryinfo — Provides information about a library
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
librarylist
librarylist — Placeholder for an alphabetical list of libraries
-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.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
libraryname
libraryname — References a library of the given name
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
librarypurpose
librarypurpose — Describes in one short sentence or phrase the purpose of a library
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
link-fail-test
link-fail-test — Declares a test that should compile but fail to link
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
link-test
link-test — Declares a test that should compile and link
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
method-group
method-group — A set of methods that are grouped together under one name
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
method
method — Declares a method, i.e., a member function
-General documentation on functions in BoostBook is provided in
- the function
- element documentation.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
namespace
namespace — Declares a namespace
-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>-
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
notes
notes — Non-normative notes about a function's semantics
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
overloaded-function
overloaded-function — An overloaded function
-General documentation on functions in BoostBook is provided in
- the function
- element documentation.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
overloaded-method
overloaded-method — An overloaded method
-General documentation on functions in BoostBook is provided in
- the function
- element documentation.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
paramtype
paramtype — The type of a function parameter
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
postconditions
postconditions — Conditions that must hold after the function returns
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
precondition
precondition — Conditions that must be met prior to executing a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
programlisting
programlisting — A sample of program code
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
purpose
purpose — A short description of an entity's use
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
rationale
rationale — Describes the rationale for a particular function's design
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
requirement
requirement — A requirement/property in the Jamfile for a testcase
-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>
.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
requires
requires — Declares the requirements of a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
returns
returns — Description of the return value of a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
run-fail-test
run-fail-test — A testcase that should compile and link, but fail on execution
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
run-test
run-test — A testcase that should compile, link, and execute
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
signature
signature — One signature of an overloaded function or method
-- 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. -
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
snippet
snippet — Pulls in a code snippet from a programlisting
element
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
source
source — Defines source code for a test
-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.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
specialization
specialization — Defines the specialization arguments for a class specialization
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
static-constant
static-constant — Declares a static constant, e.g., const int foo = 5;
.
Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
struct-specialization
struct-specialization — A specialization (full or partial) of a struct template
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
struct
struct — Declares a C++ struct
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template-arg
template-arg — A template argument in a specialization
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template-nontype-parameter
template-nontype-parameter — A nontype template parameter
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template-type-parameter
template-type-parameter — Declares a template type parameter
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template-varargs
template-varargs — Declares a variable-length list of template parameters
-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.
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
template
template — Declares the template parameters of a class or function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
testsuite
testsuite — Describes a library testsuite
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
throws
throws — Description of the exceptions thrown by a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
type
type — The type of an element or return type of a function
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
typedef
typedef — Declares a typedef
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
union-specialization
union-specialization — A specialization (full or partial) of a union template
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
union
union — Declares a C++ union or union template
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
using-class
using-class — Injects the method and function names of a class into the local scope
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
using-namespace
using-namespace — Injects the declared names from a namespace into the local scope
-Name | -Type | -Value | -Purpose | -
---|---|---|---|
last-revision | -#IMPLIED | -CDATA | -Set to $Date$ 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 | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -To use the Boost documentation tools, you will need several tools:
-xsltproc:
-libxslt
package.doxygen:
Available from http://www.doxygen.org -BoostBook provides a nearly-automatic setup script. Once - you have downloaded and - installed xsltproc, doxygen, - and (optionally) java, the setup script can - download the required DocBook stylesheets, DocBook DTD, and - (when Java is enabled) Apache FOP for PDF output. It will then - configure Boost.Build version 2 to build BoostBook - documentation. To perform the installation, execute the - script tools/boostbook/setup_boostbook.sh - from a directory where you would like the resulting XSL, DTD, - and Apache FOP installations to occur.
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
"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.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
This section describes how to manually configure Boost
- Boost version 2 (BBv@) for BoostBook. If you can use the
- automatic setup script, you should. All configuration will
- happen in the BBv2 user configuration file,
- user-config.jam
. If you do not have a copy
- of this file in your home directory, you should copy the one
- that resides in tools/build/v2
to your home
- directory. Alternatively, you can edit
- tools/build/v2/user-config.jam
directly or
- a site-wide site-config.jam
file.
To configure xsltproc manually, you
- will need to add a directive to
- user-config.jam
telling it where to find
- xsltproc. If the program is in your path,
- just add the following line to
- user-config.jam
:
using xsltproc ;-
If xsltproc is somewhere else, use
- this directive, where XSLTPROC
is the full
- pathname to xsltproc (including
- xsltproc):
using xsltproc : XSLTPROC ;-
This section describes how to configure Boost.Build to - use local copies of the DocBook DTD and XSL stylesheets to - improve processing time. You will first need to download two - packages: - -
-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
). You will want to extract this
- archive in a subdirectory!
Add the following directive telling BBv2 where to find - the DocBook DTD and XSL stylesheets:
-# BoostBook configuration -using boostbook - : DOCBOOK_XSL_DIR - : DOCBOOK_DTD_DIR - ;-
Whenever you change this directive, you will need to
- remove the bin.v2
directory that BBv2 generates.
- This is due to longstanding bug we are trying to fix.
At this point, you should be able to build HTML
- documentation for libraries that do not require Doxygen. To
- test this, change into the directory $BOOST_ROOT/libs/function/doc
and
- run the command bjam --v2
: it should produce HTML
- documentation for the Boost.Function library in the
- html
subdirectory.
Doxygen is required to build the documentation for
- several Boost libraries. You will need a recent version of
- Doxygen (most of
- the 1.3.x and 1.4.x versions will suffice). BBv2 by adding the
- following directive to
- user-config.jam
:
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, e.g.
using doxygen ;-
The relative order of declarations in
- user-config.jam
/
- site-config.jam
files is
- significant. In particular, the using
- doxygen
line should come
- after the using
- boostbook
declaration.
-
In order to generate PDF and PostScript output using
- Apache FOP, you will need a Java interpreter and Apache FOP
- (version 0.20.5 is best). Unpack Apache FOP to some
- directory. The top level directory of the FOP tool should
- contain a main script called fop.sh
on Unix
- and fop.bat
on Windows. You need to specify
- the location of that script and Java location to
- Boost.Build. Add the following to your
- user-config.jam
or
- site-config.jam
:
-
-using fop : FOP_COMMAND - : JAVA_HOME - ; --
replacing
- FOP_COMMAND
with the full path to the FOP main script, and
- replacing JAVA_HOME
with the directory where Java is
- installed. If the JAVA_HOME
environment variable is
- already set, you don't need to specify it above.
-
To test PDF generation, switch to the directory $BOOST_ROOT/libs/function/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.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Once BoostBook has been configured, we can build some
- documentation. First, change to the directory
- $BOOST_ROOT/doc
and remove (or make writable) the
- .html
files in
- $BOOST_ROOT/doc/html
. Then, 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 17.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 17.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. Requires Apache FOP. |
-|
ps | -Postscript. Requires Apache FOP. |
-
docbook | --DocBook. | -
fo | -XSL Formatting Objects | -
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
- -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>
.
- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::c_local_adjustor — Adjust to / from utc using the C API.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::c_time — Provides a uniform interface to some 'ctime' functions.
--struct c_time { - - // public static functions - std::tm * localtime(const std::time_t *, std::tm *) ; - std::tm * gmtime(const std::time_t *, std::tm *) ; - std::tm * localtime(const std::time_t *, std::tm *) ; - std::tm * gmtime(const std::time_t *, std::tm *) ; -};
Provides a uniform interface to some ctime functions and their '_r' counterparts. The '_r' functions require a pointer to a user created std::tm struct whereas the regular functions use a staticly created struct and return a pointer to that. These wrapper functions require the user to create a std::tm struct and send in a pointer to it. A pointer to the user created struct will be returned.
- -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::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.
- call_once(void (*func)() func, once_flag& flag);
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
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2001, 2002 Indiana University
Copyright © 2000, 2001 University of Notre Dame du Lac
Copyright © 2000 Jeremy Siek, Lie-Quan Lee, Andrew 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: -
-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 appears in all copies and that both that copyright - notice and this permission notice appear in supporting - documentation. Silicon Graphics makes no representations - about the suitability of this software for any purpose. It is - provided "as is" without express or implied - warranty.
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::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.
--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); -};
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 - and ). 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/destructcondition();-
Effects: - - Constructs a condition - object.
-~condition();-
Effects:
-
- Destroys *this
.
condition
notificationvoid 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.)
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
waitingtemplate<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()
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()
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()
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()
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::signals::connection — Query/disconnect a signal-slot connection.
--class connection { -public: - // construct/copy/destruct - connection(); - connection(const connection&); - connection& operator=(const connection&); - - // connection management - void disconnect() const; - bool connected() const; - - // blocking - void block(bool = true); - void unblock(); - bool blocked() const; - - // modifiers - void swap(const connection&); - - // comparisons - bool operator==(const connection&) const; - bool operator<(const connection&) const; -}; - -// specialized algorithms -void swap(connection&, connection&);
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/destructconnection();-
Effects:
-
- Sets the currently represented connection to the
- NULL connection.
Postconditions:
-
- !this->connected()
.
Throws:
-
- Will not throw.
connection(const connection& other);-
Effects:
-
- this
references
- the connection referenced by
- other
.
Throws:
-
- Will not throw.
connection& operator=(const connection& other);-
Effects:
-
- this
references
- the connection referenced by
- other
.
Throws:
-
- Will not throw.
connection
connection managementvoid disconnect() const;-
Effects:
-
- If
- this->connected()
,
- disconnects the signal and slot referenced by this;
- otherwise, this operation is a no-op.
Postconditions:
-
- !this->connected()
.
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
blockingvoid block(bool should_block = true);-
Requires:
-
- connected()
Postconditions:
-
- blocked() == should_block
Throws:
-
- Will not throw.
void unblock();-
Requires:
-
- connected()
Postconditions:
-
- !blocked()
Throws:
-
- Will not throw.
bool blocked() const;-
Returns:
-
- true
if the associated slot is either disconnected or blocked, false
otherwise.
Throws:
-
- Will not throw.
connection
modifiersvoid swap(const connection& other);-
Effects:
-
- Swaps the connections referenced in
- this
and
- other
.
Throws:
-
- Will not throw.
connection
comparisonsbool 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.
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 algorithmsvoid swap(connection& x, connection& y);-
Effects:
-
- x.swap(y)
Throws:
-
- Will not throw.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::const_formatter — Constant formatter.
--template<typename RangeT> unspecified const_formatter(const RangeT & Format);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::CV::constrained_value — A template to specify a constrained basic value type.
-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) ; -};
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.
- - - - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::contains — 'Contains' predicate
--template<typename Range1T, typename Range2T, typename PredicateT> - bool contains(const Range1T & Input, const Range2T & Test, PredicateT Comp); -template<typename Range1T, typename Range2T> - bool contains(const Range1T & Input, const Range2T & Test);
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
-An element comparison predicate
An input sequence
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::convert_string_type — Converts a string from one value_type to another.
--template<typename InputT, typename OutputT> - std::basic_string< OutputT > - convert_string_type(const std::basic_string< InputT > & inp_str);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::counted_time_rep — Time representation that uses a single integer count.
-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; - unsigned long 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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::counted_time_system — An unadjusted time system implementation.
-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) ; - time_rep_type get_time_rep(special_values) ; - 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 &) ; -};
counted_time_system
public static functionstemplate<typename T> void unused_var(const T & ) ;
time_rep_type -get_time_rep(const date_type & day, const time_duration_type & tod, - date_time::dst_flags dst = not_dst) ;
time_rep_type get_time_rep(special_values sv) ;
date_type get_date(const time_rep_type & val) ;
time_duration_type get_time_of_day(const time_rep_type & val) ;
std::string zone_name(const time_rep_type & ) ;
bool is_equal(const time_rep_type & lhs, const time_rep_type & rhs) ;
bool is_less(const time_rep_type & lhs, const time_rep_type & rhs) ;
time_rep_type -add_days(const time_rep_type & base, const date_duration_type & dd) ;
time_rep_type -subtract_days(const time_rep_type & base, const date_duration_type & dd) ;
time_rep_type -subtract_time_duration(const time_rep_type & base, - const time_duration_type & td) ;
time_rep_type -add_time_duration(const time_rep_type & base, time_duration_type td) ;
time_duration_type -subtract_times(const time_rep_type & lhs, const time_rep_type & rhs) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::custom_time_zone — A real time zone.
--class custom_time_zone : public boost::local_time::time_zone { -public: - // types - typedef boost::posix_time::time_duration time_duration_type; - typedef time_zone base_type; - typedef base_type::string_type string_type; - typedef base_type::stringstream_type stringstream_type; - - // construct/copy/destruct - custom_time_zone(const time_zone_names &, const time_duration_type &, - const dst_adjustment_offsets &, - boost::shared_ptr< dst_calc_rule >); - ~custom_time_zone(); - - // public member functions - virtual std::string dst_zone_abbrev() const; - virtual std::string std_zone_abbrev() const; - virtual std::string dst_zone_name() const; - virtual std::string std_zone_name() const; - virtual bool has_dst() const; - virtual posix_time::ptime dst_local_start_time(gregorian::greg_year) const; - virtual posix_time::ptime dst_local_end_time(gregorian::greg_year) const; - virtual time_duration_type base_utc_offset() const; - virtual time_duration_type dst_offset() const; - virtual string_type to_posix_string() const; -};
custom_time_zone
public member functionsvirtual std::string dst_zone_abbrev() const;
virtual std::string std_zone_abbrev() const;
virtual std::string dst_zone_name() const;
virtual std::string std_zone_name() const;
virtual bool has_dst() const;
virtual posix_time::ptime dst_local_start_time(gregorian::greg_year y) const;
virtual posix_time::ptime dst_local_end_time(gregorian::greg_year y) const;
virtual time_duration_type base_utc_offset() const;
virtual time_duration_type dst_offset() const;
virtual string_type to_posix_string() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::data_not_accessible —
--struct data_not_accessible { - // construct/copy/destruct - data_not_accessible(); - data_not_accessible(const std::string &); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_duration — Duration type with date level resolution.
-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() ; -};
date_duration
construct/copy/destructdate_duration(duration_rep day_count);
date_duration(special_values sv);-
construct from special_values - only works when instantiated with duration_traits_adapted
-date_duration(const date_duration< duration_rep_traits > & other);
date_duration
public member functionsduration_rep get_rep() const;
bool is_special() const;
duration_rep_type days() const;
bool operator==(const date_duration & rhs) const;
bool operator<(const date_duration & rhs) const;
date_duration operator-=(const date_duration & rhs) ;
date_duration operator+=(const date_duration & rhs) ;
date_duration operator-() const;
date_duration< duration_rep_traits > operator/=(int divisor) ;
date_duration< duration_rep_traits > operator/(int divisor) ;
bool is_negative() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_facet —
-template<typename date_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > -class date_facet { -public: - // types - typedef date_type::duration_type duration_type; - typedef date_type::day_of_week_type day_of_week_type; - typedef date_type::day_type day_type; - typedef date_type::month_type month_type; - typedef boost::date_time::period< date_type, duration_type > period_type; - typedef std::basic_string< CharT > string_type; - typedef CharT char_type; - typedef boost::date_time::period_formatter< CharT > period_formatter_type; - typedef boost::date_time::special_values_formatter< CharT > special_values_formatter_type; - typedef std::vector< std::basic_string< CharT > > input_collection_type; - typedef date_generator_formatter< date_type, CharT > date_gen_formatter_type; - typedef partial_date< date_type > partial_date_type; - typedef nth_kday_of_month< date_type > nth_kday_type; - typedef first_kday_of_month< date_type > first_kday_type; - typedef last_kday_of_month< date_type > last_kday_type; - typedef first_kday_after< date_type > kday_after_type; - typedef first_kday_before< date_type > kday_before_type; - - // construct/copy/destruct - date_facet(::size_t = 0); - date_facet(const char_type *, const input_collection_type &, ::size_t = 0); - date_facet(const char_type *, - period_formatter_type = period_formatter_type(), - special_values_formatter_type = special_values_formatter_type(), - date_gen_formatter_type = date_gen_formatter_type(), - ::size_t = 0); - - // public member functions - std::locale::id & __get_id(void) const; - void format(const char_type *const) ; - virtual void set_iso_format() ; - virtual void set_iso_extended_format() ; - void month_format(const char_type *const) ; - void weekday_format(const char_type *const) ; - void period_formatter(period_formatter_type) ; - void special_values_formatter(const special_values_formatter_type &) ; - void short_weekday_names(const input_collection_type &) ; - void long_weekday_names(const input_collection_type &) ; - void short_month_names(const input_collection_type &) ; - void long_month_names(const input_collection_type &) ; - void date_gen_phrase_strings(const input_collection_type &, - typename date_gen_formatter_type::phrase_elements = date_gen_formatter_type::first) ; - OutItrT put(OutItrT, std::ios_base &, char_type, const date_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const duration_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const month_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const day_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const day_of_week_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const period_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const partial_date_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const nth_kday_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const first_kday_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const last_kday_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const kday_before_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const kday_after_type &) const; - - // protected member functions - tm init_tm(tm &) const; - virtual OutItrT - do_put_special(OutItrT, std::ios_base &, char_type, - const boost::date_time::special_values) const; - virtual OutItrT - do_put_tm(OutItrT, std::ios_base &, char_type, const tm &, string_type) const; - - static const char_type long_weekday_format; - static const char_type short_weekday_format; - static const char_type long_month_format; - static const char_type short_month_format; - static const char_type default_period_separator; - static const char_type standard_format_specifier; - static const char_type iso_format_specifier; - static const char_type iso_format_extended_specifier; - static const char_type default_date_format; - static std::locale::id id; -};
Class that provides format based I/O facet for date types.
-This class allows the formatting of dates by using format string. Format strings are:
-A => long_weekday_format - Full name Ex: Tuesday
a => short_weekday_format - Three letter abbreviation Ex: Tue
B => long_month_format - Full name Ex: October
b => short_month_format - Three letter abbreviation Ex: Oct
x => standard_format_specifier - defined by the locale
Y-%b-%d => default_date_format - YYYY-Mon-dd
Default month format == b Default weekday format == a
-date_facet
construct/copy/destructdate_facet(::size_t a_ref = 0);
date_facet(const char_type * format, - const input_collection_type & short_month_names, - ::size_t ref_count = 0);
date_facet(const char_type * format, - period_formatter_type period_formatter = period_formatter_type(), - special_values_formatter_type special_values_formatter = special_values_formatter_type(), - date_gen_formatter_type dg_formatter = date_gen_formatter_type(), - ::size_t ref_count = 0);
date_facet
public member functionsstd::locale::id & __get_id(void ) const;
void format(const char_type *const format) ;
virtual void set_iso_format() ;
virtual void set_iso_extended_format() ;
void month_format(const char_type *const format) ;
void weekday_format(const char_type *const format) ;
void period_formatter(period_formatter_type period_formatter) ;
void special_values_formatter(const special_values_formatter_type & svf) ;
void short_weekday_names(const input_collection_type & short_weekday_names) ;
void long_weekday_names(const input_collection_type & long_weekday_names) ;
void short_month_names(const input_collection_type & short_month_names) ;
void long_month_names(const input_collection_type & long_month_names) ;
void date_gen_phrase_strings(const input_collection_type & new_strings, - typename date_gen_formatter_type::phrase_elements beg_pos = date_gen_formatter_type::first) ;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const date_type & d) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const duration_type & dd) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const month_type & m) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const day_type & day) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const day_of_week_type & dow) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const period_type & p) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const partial_date_type & pd) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const nth_kday_type & nkd) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const first_kday_type & fkd) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const last_kday_type & lkd) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const kday_before_type & fkb) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const kday_after_type & fka) const;
date_facet
protected member functionstm init_tm(tm & tm_value) const;
virtual OutItrT -do_put_special(OutItrT next, std::ios_base & , char_type , - const boost::date_time::special_values sv) const;
virtual OutItrT -do_put_tm(OutItrT next, std::ios_base & a_ios, char_type fill_char, - const tm & tm_value, string_type a_format) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_formatter — Convert a date to string using format policies.
-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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_generator_formatter — Formats date_generators for output.
-template<typename date_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > -class date_generator_formatter { -public: - // types - typedef partial_date< date_type > partial_date_type; - typedef nth_kday_of_month< date_type > nth_kday_type; - typedef first_kday_of_month< date_type > first_kday_type; - typedef last_kday_of_month< date_type > last_kday_type; - typedef first_kday_after< date_type > kday_after_type; - typedef first_kday_before< date_type > kday_before_type; - typedef CharT char_type; - typedef std::basic_string< char_type > string_type; - typedef std::vector< string_type > collection_type; - - // construct/copy/destruct - date_generator_formatter(); - date_generator_formatter(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &); - - // public member functions - void elements(const collection_type &, phrase_elements = first) ; - template<typename facet_type> - OutItrT put_partial_date(OutItrT, std::ios_base &, CharT, - const partial_date_type &, const facet_type &) const; - template<typename facet_type> - OutItrT put_nth_kday(OutItrT, std::ios_base &, CharT, - const nth_kday_type &, const facet_type &) const; - template<typename facet_type> - OutItrT put_first_kday(OutItrT, std::ios_base &, CharT, - const first_kday_type &, const facet_type &) const; - template<typename facet_type> - OutItrT put_last_kday(OutItrT, std::ios_base &, CharT, - const last_kday_type &, const facet_type &) const; - template<typename facet_type> - OutItrT put_kday_before(OutItrT, std::ios_base &, CharT, - const kday_before_type &, const facet_type &) const; - template<typename facet_type> - OutItrT put_kday_after(OutItrT, std::ios_base &, CharT, - const kday_after_type &, const facet_type &) const; - - // private member functions - OutItrT put_string(OutItrT, const string_type &) const; - - static const char_type first_string; - static const char_type second_string; - static const char_type third_string; - static const char_type fourth_string; - static const char_type fifth_string; - static const char_type last_string; - static const char_type before_string; - static const char_type after_string; - static const char_type of_string; -};
Formatting of date_generators follows specific orders for the various types of date_generators.
-partial_date => "dd Month"
nth_day_of_the_week_in_month => "nth weekday of month"
first_day_of_the_week_in_month => "first weekday of month"
last_day_of_the_week_in_month => "last weekday of month"
first_day_of_the_week_after => "weekday after"
first_day_of_the_week_before => "weekday before" While the order of the elements in these phrases cannot be changed, the elements themselves can be. Weekday and Month get their formats and names from the date_facet. The remaining elements are stored in the date_generator_formatter and can be customized upon construction or via a member function. The default elements are those shown in the examples above.
date_generator_formatter
construct/copy/destructdate_generator_formatter();
date_generator_formatter(const string_type & first, - const string_type & second, - const string_type & third, - const string_type & fourth, - const string_type & fifth, const string_type & last, - const string_type & before, - const string_type & after, const string_type & of);
date_generator_formatter
public member functionsvoid elements(const collection_type & new_strings, - phrase_elements beg_pos = first) ;-
The order of the strings in the given collection is important. They must follow:
-first, second, third, fourth, fifth, last, before, after, of.
It is not necessary to send in a complete set if only a few elements are to be replaced as long as the correct beg_pos is used.
-Ex: To keep the default first through fifth elements, but replace the rest with a collection of:
-"final", "prior", "following", "in". The beg_pos of date_generator_formatter::last would be used.
template<typename facet_type> - OutItrT put_partial_date(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const partial_date_type & pd, - const facet_type & facet) const;
template<typename facet_type> - OutItrT put_nth_kday(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const nth_kday_type & nkd, const facet_type & facet) const;
template<typename facet_type> - OutItrT put_first_kday(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const first_kday_type & fkd, - const facet_type & facet) const;
template<typename facet_type> - OutItrT put_last_kday(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const last_kday_type & lkd, const facet_type & facet) const;
template<typename facet_type> - OutItrT put_kday_before(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const kday_before_type & fkb, - const facet_type & facet) const;
template<typename facet_type> - OutItrT put_kday_after(OutItrT next, std::ios_base & a_ios, CharT a_fill, - const kday_after_type & fka, - const facet_type & facet) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_generator_parser — Class for date_generator parsing.
-template<typename date_type, typename charT> -class date_generator_parser { -public: - // types - typedef std::basic_string< charT > string_type; - typedef std::istreambuf_iterator< charT > stream_itr_type; - typedef date_type::month_type month_type; - typedef date_type::day_of_week_type day_of_week_type; - typedef date_type::day_type day_type; - typedef string_parse_tree< charT > parse_tree_type; - typedef parse_tree_type::parse_match_result_type match_results; - typedef std::vector< std::basic_string< charT > > collection_type; - typedef partial_date< date_type > partial_date_type; - typedef nth_kday_of_month< date_type > nth_kday_type; - typedef first_kday_of_month< date_type > first_kday_type; - typedef last_kday_of_month< date_type > last_kday_type; - typedef first_kday_after< date_type > kday_after_type; - typedef first_kday_before< date_type > kday_before_type; - typedef charT char_type; - - // construct/copy/destruct - date_generator_parser(); - date_generator_parser(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &); - date_generator_parser(const date_generator_parser< date_type, charT > *); - - // public member functions - void element_strings(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &) ; - void element_strings(const collection_type &) ; - template<typename facet_type> - partial_date_type - get_partial_date_type(stream_itr_type &, stream_itr_type &, - std::ios_base &, const facet_type &) const; - template<typename facet_type> - nth_kday_type - get_nth_kday_type(stream_itr_type &, stream_itr_type &, std::ios_base &, - const facet_type &) const; - template<typename facet_type> - first_kday_type - get_first_kday_type(stream_itr_type &, stream_itr_type &, std::ios_base &, - const facet_type &) const; - template<typename facet_type> - last_kday_type - get_last_kday_type(stream_itr_type &, stream_itr_type &, std::ios_base &, - const facet_type &) const; - template<typename facet_type> - kday_before_type - get_kday_before_type(stream_itr_type &, stream_itr_type &, - std::ios_base &, const facet_type &) const; - template<typename facet_type> - kday_after_type - get_kday_after_type(stream_itr_type &, stream_itr_type &, std::ios_base &, - const facet_type &) const; - - // private member functions - void extract_element(stream_itr_type &, stream_itr_type &, - typename date_generator_parser::phrase_elements) const; - - static const char_type first_string; - static const char_type second_string; - static const char_type third_string; - static const char_type fourth_string; - static const char_type fifth_string; - static const char_type last_string; - static const char_type before_string; - static const char_type after_string; - static const char_type of_string; -};
The elements of a date_generator "phrase" are parsed from the input stream in a particular order. All elements are required and the order in which they appear cannot change, however, the elements themselves can be changed. The default elements and their order are as follows:
-partial_date => "dd Month"
nth_day_of_the_week_in_month => "nth weekday of month"
first_day_of_the_week_in_month => "first weekday of month"
last_day_of_the_week_in_month => "last weekday of month"
first_day_of_the_week_after => "weekday after"
first_day_of_the_week_before => "weekday before"
Weekday and Month names and formats are handled via the date_input_facet.
-TODO: add doc-comments for which elements can be changed
-date_generator_parser
construct/copy/destructdate_generator_parser();
date_generator_parser(const string_type & first, const string_type & second, - const string_type & third, const string_type & fourth, - const string_type & fifth, const string_type & last, - const string_type & before, const string_type & after, - const string_type & of);
date_generator_parser(const date_generator_parser< date_type, charT > * dgp);
date_generator_parser
public member functionsvoid element_strings(const string_type & first, const string_type & second, - const string_type & third, const string_type & fourth, - const string_type & fifth, const string_type & last, - const string_type & before, const string_type & after, - const string_type & of) ;
void element_strings(const collection_type & col) ;
template<typename facet_type> - partial_date_type - get_partial_date_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
template<typename facet_type> - nth_kday_type - get_nth_kday_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
template<typename facet_type> - first_kday_type - get_first_kday_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
template<typename facet_type> - last_kday_type - get_last_kday_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
template<typename facet_type> - kday_before_type - get_kday_before_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
template<typename facet_type> - kday_after_type - get_kday_after_type(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const facet_type & facet) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_input_facet — Input facet.
-template<typename date_type, typename CharT, - typename InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > > -class date_input_facet { -public: - // types - typedef date_type::duration_type duration_type; - typedef date_type::day_of_week_type day_of_week_type; - typedef date_type::day_type day_type; - typedef date_type::month_type month_type; - typedef date_type::year_type year_type; - typedef boost::date_time::period< date_type, duration_type > period_type; - typedef std::basic_string< CharT > string_type; - typedef CharT char_type; - typedef boost::date_time::period_parser< date_type, CharT > period_parser_type; - typedef special_values_parser< date_type, CharT > special_values_parser_type; - typedef std::vector< std::basic_string< CharT > > input_collection_type; - typedef format_date_parser< date_type, CharT > format_date_parser_type; - typedef date_generator_parser< date_type, CharT > date_gen_parser_type; - typedef partial_date< date_type > partial_date_type; - typedef nth_kday_of_month< date_type > nth_kday_type; - typedef first_kday_of_month< date_type > first_kday_type; - typedef last_kday_of_month< date_type > last_kday_type; - typedef first_kday_after< date_type > kday_after_type; - typedef first_kday_before< date_type > kday_before_type; - - // construct/copy/destruct - date_input_facet(::size_t = 0); - date_input_facet(const string_type &, ::size_t = 0); - date_input_facet(const string_type &, const format_date_parser_type &, - const special_values_parser_type &, - const period_parser_type &, const date_gen_parser_type &, - ::size_t = 0); - - // public member functions - void format(const char_type *const) ; - virtual void set_iso_format() ; - virtual void set_iso_extended_format() ; - void month_format(const char_type *const) ; - void weekday_format(const char_type *const) ; - void year_format(const char_type *const) ; - void period_parser(period_parser_type) ; - void short_weekday_names(const input_collection_type &) ; - void long_weekday_names(const input_collection_type &) ; - void short_month_names(const input_collection_type &) ; - void long_month_names(const input_collection_type &) ; - void date_gen_element_strings(const input_collection_type &) ; - void date_gen_element_strings(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &) ; - void special_values_parser(special_values_parser_type) ; - InItrT get(InItrT &, InItrT &, std::ios_base &, date_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, month_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, day_of_week_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, day_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, year_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, duration_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, period_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, nth_kday_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, partial_date_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, first_kday_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, last_kday_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, kday_before_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, kday_after_type &) const; - - static const char_type long_weekday_format; - static const char_type short_weekday_format; - static const char_type long_month_format; - static const char_type short_month_format; - static const char_type four_digit_year_format; - static const char_type two_digit_year_format; - static const char_type default_period_separator; - static const char_type standard_format_specifier; - static const char_type iso_format_specifier; - static const char_type iso_format_extended_specifier; - static const char_type default_date_format; - static std::locale::id id; -};
date_input_facet
construct/copy/destructdate_input_facet(::size_t a_ref = 0);
date_input_facet(const string_type & format, ::size_t a_ref = 0);
date_input_facet(const string_type & format, - const format_date_parser_type & date_parser, - const special_values_parser_type & sv_parser, - const period_parser_type & per_parser, - const date_gen_parser_type & date_gen_parser, - ::size_t ref_count = 0);
date_input_facet
public member functionsvoid format(const char_type *const format) ;
virtual void set_iso_format() ;
virtual void set_iso_extended_format() ;
void month_format(const char_type *const format) ;
void weekday_format(const char_type *const format) ;
void year_format(const char_type *const format) ;
void period_parser(period_parser_type period_parser) ;
void short_weekday_names(const input_collection_type & weekday_names) ;
void long_weekday_names(const input_collection_type & weekday_names) ;
void short_month_names(const input_collection_type & month_names) ;
void long_month_names(const input_collection_type & month_names) ;
void date_gen_element_strings(const input_collection_type & col) ;
void date_gen_element_strings(const string_type & first, - const string_type & second, - const string_type & third, - const string_type & fourth, - const string_type & fifth, - const string_type & last, - const string_type & before, - const string_type & after, - const string_type & of) ;
void special_values_parser(special_values_parser_type sv_parser) ;
InItrT get(InItrT & from, InItrT & to, std::ios_base & , date_type & d) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & , month_type & m) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & , - day_of_week_type & wd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & , day_type & d) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & , year_type & y) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - duration_type & dd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, period_type & p) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - nth_kday_type & nkd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - partial_date_type & pd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - first_kday_type & fkd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - last_kday_type & lkd) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - kday_before_type & fkb) const;
InItrT get(InItrT & from, InItrT & to, std::ios_base & a_ios, - kday_after_type & fka) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_itr — Overrides the base date iterator providing hook for functors.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_itr_base — Base date iterator type.
-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 &) ; -};
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
public member functionsdate_itr_base & operator++() ;
date_itr_base & operator--() ;
virtual duration_type get_offset(const date_type & current) const;
virtual duration_type get_neg_offset(const date_type & current) const;
date_type operator *() ;
date_type * operator->() ;
bool operator<(const date_type & d) ;
bool operator<=(const date_type & d) ;
bool operator>(const date_type & d) ;
bool operator>=(const date_type & d) ;
bool operator==(const date_type & d) ;
bool operator!=(const date_type & d) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::date_names_put — Output facet base class for gregorian dates.
-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; - typedef charT char_type; - - // construct/copy/destruct - date_names_put(); - - // public member functions - std::locale::id & __get_id(void) const; - 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 const char_type default_special_value_names; - static const char_type separator; - static std::locale::id id; -};
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
public member functionsstd::locale::id & __get_id(void ) const;
void put_special_value(iter_type & oitr, special_value_enum sv) const;
void put_month_short(iter_type & oitr, month_enum moy) const;
void put_month_long(iter_type & oitr, month_enum moy) const;
void put_weekday_short(iter_type & oitr, weekday_enum wd) const;
void put_weekday_long(iter_type & oitr, weekday_enum wd) const;
bool has_date_sep_chars() const;
void year_sep_char(iter_type & oitr) const;
void month_sep_char(iter_type & oitr) const;
void day_sep_char(iter_type & oitr) const;
ymd_order_spec date_order() const;
month_format_spec month_format() const;
date_names_put
protected member functionsvirtual void do_put_month_short(iter_type & oitr, month_enum moy) const;
virtual void do_put_month_long(iter_type & oitr, month_enum moy) const;
virtual void -do_put_special_value(iter_type & oitr, special_value_enum sv) 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 & oitr) const;
virtual void do_month_sep_char(iter_type & oitr) const;
virtual void do_day_sep_char(iter_type & oitr) const;
virtual ymd_order_spec do_date_order() const;
virtual month_format_spec do_month_format() const;
void put_string(iter_type & oi, const charT *const s) const;
void put_string(iter_type & oi, const string_type & s1) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2001-2005 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)
Table of Contents
-- A set of date-time libraries based on generic programming concepts. -
-This documentation is also available in PDF format. It can be found at: -
-http://www.crystalclearsoftware.com/libraries/date_time/date_time.pdf |
- In addition, a full doxygen reference can be found at: -
-http://www.crystalclearsoftware.com/libraries/date_time/ref_guide/index.html |
- The most current version of the documentation can be found at: -
-http://www.crystalclearsoftware.com/libraries/date_time/index.html |
- 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. -
-- 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: -
-- 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. -
- -- 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. -
-Last revised: June 12, 2005 at 20:53:10 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
As of version 1.33, the date_time library utilizes a new IO streaming system. This new system gives the user great control over how dates and times can be represented. The customization options can be broken down into two groups: format flags and string elements. Format flags provide flexibility in the order of the date elements as well as the type. Customizing the string elements allows the replacement of built in strings from month names, weekday names, and other strings used in the IO.
-The output system is based on a date_facet (derived from std::facet), while the input system is based on a date_input_facet (also derived from std::facet). The time and local_time facets are derived from these base types. The output system utilizes three formatter objects, whereas the input system uses four parser objects. These formatter and parser objetcs are also customizable.
-It is important to note, that while all the examples shown here use narrow streams, there are wide stream facets available as well (see IO Objects for a complete list).
-It should be further noted that not all compilers are capable of using this IO system. For those compilers the IO system used in previous date_time
versions is still available. The "legacy IO" is automatically selected for these compilers, however, the legacy IO system can be manually selected by defining USE_DATE_TIME_PRE_1_33_FACET_IO
. See the Build-Compiler Information for more information.
When an error occurs during the input streaming process, the std::ios_base::failbit
will (always) be set on the stream. It is also possible to have exceptions thrown when an error occurs. To "turn on" these exceptions, call the stream's exceptions
function with a parameter of std::ios_base::failbit
.
// "Turning on" exceptions -date d(not_a_date_time); -std::stringstream ss; -ss.exceptions(std::ios_base::failbit); -ss.str("204-Jan-01"); -ss >> d; // throws bad_year exception AND sets failbit on stream-
//example to customize output to be "LongWeekday LongMonthname day, year" -// "%A %b %d, %Y" -date d(2005,Jun,25); -date_facet* facet(new date_facet("%A %B %d, %Y")); -std::cout.imbue(std::locale(std::cout.getloc(), facet)); -std::cout << d << std::endl; -// "Saturday June 25, 2005"-
Many of the format flags this new system uses for output are those used by strftime(...)
, but not all. Some new flags have been added, and others overridden. The input system supports only specific flags, therefore, not all flags that work for output will work with input (we are currently working to correct this situation).
The following tables list the all the flags available for both date_time IO as well as strftime. Format flags marked with a single asterisk (*) have a behavior unique to date_time. Those flags marked with an exclamation point (!) are not usable for input (at this time). The first table is for dates, and the second table is for times. -
- -Format Specifier | -Description | -
---|---|
Example | |
%a |
-Abbreviated weekday name | -
"Mon" => Monday | |
%A |
-Long weekday name | -
"Monday" | |
%b |
-Abbreviated month name | -
"Feb" => February | |
%B |
-Full month name | -
"February" | |
%c ! |
-The preferred date and time representation for the current locale. | -
%C ! |
-The century number (year/100) as a 2-digit integer. | -
%d |
-Day of the month as decimal 01 to 31 | -
%D ! |
-Equivalent to %m/%d/%y | -
%e ! |
-Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space | -
%G ! |
-This has the same format and value as %y, except that if the ISO week number belongs to the previous or next year, that year is used instead. | -
%g ! |
-Like %G, but without century. | -
%h ! |
-Equivalent to %b | -
%j |
-Day of year as decimal from 001 to 366 for leap years, 001 - 365 for non-leap years. | -
"060" => Feb-29 | |
%m |
-Month name as a decimal 01 to 12 | -
"01" => January | |
%u ! |
-The day of the week as a decimal, range 1 to 7, Monday being 1. | -
%U |
-The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. In 2005, Jan 1st falls on a Saturday, so therefore it falls within week 00 of 2005 (week 00 spans 2004-Dec-26 to 2005-Jan-01. This also happens to be week 53 of 2004). | -
date d(2005, Jan, 1); // Saturday - // with format %U - ss << d; // "00" - d += day(1); // Sunday - ss << d; // "01" beginning of week 1 | |
%V ! |
-The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. | -
%w |
-Weekday as decimal number 0 to 6 | -
"0" => Sunday | |
%W |
-Week number 00 to 53 where Monday is first day of week 1 | -
date d(2005, Jan, 2); // Sunday - // with format %W - ss << d; // "00" - d += day(1); // Monday - ss << d; // "01" beginning of week 1 | |
%x |
-Implementation defined date format from the locale. | -
date d(2005,Oct,31); - date_facet* f = new date_facet("%x"); - - locale loc = locale(locale("en_US"), f); - cout.imbue(loc); - cout << d; // "10/31/2005" - - loc = locale(locale("de_DE"), f); - cout.imbue(loc); - cout << d; // "31.10.2005" | |
%y |
-Two digit year | -
"05" => 2005 | |
%Y |
-Four digit year | -
"2005" | |
%Y-%b-%d |
-Default date format | -
"2005-Apr-01" | |
%Y%m%d |
-ISO format | -
"20050401" | |
%Y-%m-%d |
-ISO extended format | -
"2005-04-01" |
Format Specifier | -Description | -
---|---|
Example | |
%- *! |
-Placeholder for the sign of a duration. Only displays when the duration is negative. | -
"-13:15:16" | |
%+ *! |
-Placeholder for the sign of a duration. Always displays for both positive and negative. | -
"+13:15:16" | |
%f |
-Fractional seconds are always used, even when their value is zero | -
"13:15:16.000000" | |
%F * |
-Fractional seconds are used only when their value is not zero. | -
"13:15:16" - "05:04:03.001234" - | |
%I ! |
-The hour as a decimal number using a 12-hour clock | -
%k ! |
-The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. | -
%l ! |
-The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. | -
%p ! |
-Either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale. | -
%P ! |
-Like %p but in lowercase: `am' or `pm' or a corresponding string for the current locale. | -
%r ! |
-The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to `%I:%M:%S %p' | -
%R ! |
-The time in 24-hour notation (%H:%M) | -
%s * |
-Seconds with fractional seconds. | -
"59.000000" | |
%S |
-Seconds only | -
"59" | |
%T ! |
-The time in 24-hour notation (%H:%M:%S) | -
%q |
-ISO time zone (output only). This flag is ignored when using the time_facet with a ptime. | -
"-0700" // Mountain Standard Time | |
%Q |
-ISO extended time zone (output only). This flag is ignored when using the time_facet with a ptime. | -
"-05:00" // Eastern Standard Time | |
%z *! |
-Abbreviated time zone (output only). This flag is ignored when using the time_facet with a ptime. | -
"MST" // Mountain Standard Time | |
%Z *! |
-Full time zone name (output only). This flag is ignored when using the time_facet with a ptime. | -
"EDT" // Eastern Daylight Time | |
%ZP * |
-Posix time zone string (available to both input and output). This flag is ignored when using the time_facet with a ptime. For complete details on posix time zone strings, see posix_time_zone class. | -
"EST-05EDT+01,M4.1.0/02:00,M10.5.0/02:00" | |
%x %X |
-Implementation defined date/time format from the locale. | -
date d(2005,Oct,31); - ptime pt(d, hours(20)); - time_facet* f = new time_facet("%x %X"); - - locale loc = locale(locale("en_US"), f); - cout.imbue(loc); - cout << pt; // "10/31/2005 08:00:00 PM" - - loc = locale(locale("de_DE"), f); - cout.imbue(loc); - cout << pt; // "31.10.2005 20:00:00" | |
%Y%m%dT%H%M%S%F%q |
-ISO format | -
"20051015T131211-0700" - // Oct 15, 2005 13:12:11 MST - | |
%Y-%m-%d %H:%M:%S%F%Q |
-Extended ISO format | -
"2005-10-15 13:12:11-07:00" | |
%Y-%b-%d %H:%M:%S%F %z |
-Default format used when outputting ptime and local_date_time. | -
"2005-Oct-15 13:12:11 MST" | |
%Y-%b-%d %H:%M:%S%F %ZP |
-Default format used when inputting ptime and local_date_time. | -
"2005-Oct-15 13:12:11 MST-07" | |
%-%H:%M:%S%F ! |
-Default time_duration format for output. Sign will only be displayed for negative durations. | -
"-13:14:15.003400" | |
%H:%M:%S%F |
-Default time_duration format for input. | -
"13:14:15.003400" |
* Signifies flags that have a behavior unique to date_time
.
! Signifies flags that currently do not work for input.
-The following table lists the available facets.
-Output | -Input | -
---|---|
date_facet |
-date_input_facet |
-
wdate_facet |
-wdate_input_facet |
-
time_facet |
-time_input_facet |
-
wtime_facet |
-wtime_input_facet |
-
-local_time_facet * |
-
-local_time_input_facet * |
-
-wlocal_time_facet * |
-
-wlocal_time_input_facet * |
-
- * These links lead to the time_facet
and time_input_facet
reference sections. They are not actual classes but typedefs.
-
To implement the new i/o facets the date-time library uses a number of new parsers and formatters. These classes are available for users that want to implement specialized input/output routines.
-Output | -Input | -
---|---|
period_formatter |
-period_parser |
-
date_generator_formatter |
-date_generator_parser |
-
special_values_formatter |
-special_values_parser |
-
- | format_date_parser |
-
The boost::date_time::date_facet
enables users to have significant control over the output streaming of dates (and other gregorian objects). The date_facet is typedef'd in the gregorian
namespace as date_facet
and wdate_facet
.
-
Syntax | -Description | -
---|---|
date_facet() |
-Default constructor | -
date_facet(...) - Parameters: - char_type* format - input_collection_type |
-Format given will be used for date output. All other formats will use their defaults. Collection is the set of short names to be used for months. All other name collections will use their defaults. | -
date_facet(...) - Parameters: - char_type* format - period_formatter_type - special_values_formatter_type - date_gen_formatter_type |
-Format given will be used for date output. The remaining parameters are formatter objects. Further details on these objects can be found here. This constructor also provides default arguments for all parameters except the format. Therefore, date_facet("%m %d %Y") will work. |
-
Syntax | -Description | -
---|---|
Example | |
void format(char_type*) |
-Set the format for dates. | -
date_facet* f = new date_facet(); -f->format("%m %d %Y"); | |
void set_iso_format() |
-Sets the date format to ISO | -
f->set_iso_format(); -// "%Y%m%d" | |
void set_iso_extended_format() |
-Sets the date format to ISO Extended | -
f->set_iso_extended_format(); -// "%Y-%m-%d" | |
void month_format(char_type*) |
-Set the format for months when they are 'put' individually. | -
f->month_format("%B"); -ss << greg_month(12); // "December" | |
void weekday_format(char_type*) |
-Set the format for weekdays when they are 'put' individually. | -
f->weekday_format("%a"); -ss << greg_weekday(2); // "Tue" | |
void period_formatter(...) - Parameter: - period_formatter_type |
-Replaces the period formatter object with a user created one. | -
see the tutorial for a complete example. | |
void special_values_formatter(...) - Parameter: - special_values_formatter_type |
-Replaces the special_values formatter object with a user created one. | -
see the tutorial for a complete example. | |
void date_gen_phrase_strings(...) - Parameters: - input_collection_type - date_gen_formatter_type:: - phrase_elements |
-Sets new date generator phrase strings in date_gen_formatter. The input collection is a vector of strings (for details on these strings see date generator formatter/parser documentation). The phrase_elements parameter is an enum, defined in the date_generator_formatter object, that has a default value of 'first'. It is used to indicate what the position of the first string in the collection will be. | -
void short_weekday_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'putting' short weekdays. | -
see the tutorial for a complete example. | |
void long_weekday_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'putting' long weekdays. | -
see the tutorial for a complete example. | |
void short_month_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'putting' short months. | -
see the tutorial for a complete example. | |
void long_month_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'putting' long months. | -
see the tutorial for a complete example. | |
OutItrT put(...) - Common parameters for all - 'put' functions: - OutItrT - ios_base - char_type - Unique parameter for 'put' funcs: - gregorian object |
-There are 12 put functions in the date_facet. The common paraeters are: an iterator pointing to the next item in the stream, an ios_base object, and the fill character. Each unique gregorian object has it's own put function. Each unique put function is described below. | -
OutItrT put(..., date) |
-Puts a date object into the stream using the format set by format(...) or the default. |
-
OutItrT put(..., days) |
-Puts a days object into the stream as a number. | -
OutItrT put(..., month) |
-Puts a month object into the stream using the format set by month_format(...) or the default. |
-
OutItrT put(..., day) |
-Puts a day of month object into the stream as a two digit number. | -
"01" // January 1st | |
OutItrT put(..., day_of_week) |
-Puts a day of week object into the stream using the format set by weekday_format(...) or the default. |
-
OutItrT put(..., date_period) |
-Puts a date_period into the stream. The format of the dates will use the format set by format(..) or the default date format. The type of period (open or closed range) and the delimiters used are those used by the period_formatter. |
-
OutItrT put(..., partial_date) |
-Puts a partial_date date_generator object into the stream. The month format used is set by month_format(..) or the default. The day of month is represented as a two digit number. |
-
"01 Jan" // default formats -"01 January" // long month format | |
OutItrT put(..., date_generator) - Date Generator Type: - nth_day_of_the_week_in_month |
-Puts a nth_day_of_the_week_in_month object into the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_formatter. |
-
"third Fri in May" // defaults | |
OutItrT put(..., date_generator) - Date Generator Type: - first_day_of_the_week_in_month |
-Puts a first_day_of_the_week_in_month object into the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_formatter. |
-
"first Wed of Jun" // defaults | |
OutItrT put(..., date_generator) - Date Generator Type: - last_day_of_the_week_in_month |
-Puts a last_day_of_the_week_in_month object into the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_formatter. |
-
"last Tue of Mar" // defaults | |
OutItrT put(..., date_generator) - Date Generator Type: - first_day_of_the_week_after |
-Puts a first_day_of_the_week_after object into the stream. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_formatter. |
-
"first Sat after" // defaults | |
OutItrT put(..., date_generator) - Date Generator Type: - first_day_of_the_week_before |
-Puts a first_day_of_the_week_before object into the stream. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_formatter. |
-
"first Mon before" // defaults |
The boost::date_time::date_input_facet
enables users to have significant control how dates (and other gregorian objects) are streamed in. The date_input_facet is typedef'd in the gregorian
namespace as date_input_facet
and wdate_input_facet
.
-
Syntax | -Description | -
---|---|
date_input_facet() |
-Default constructor | -
date_input_facet(string_type format) |
-Format given will be used for date input. All other formats will use their defaults. | -
date_input_facet(...) - Parameters: - string_type format - format_date_parser_type - special_values_parser_type - period_parser_type - date_gen_parser_type |
-Format given will be used for date input. The remaining parameters are parser objects. Further details on these objects can be found here. | -
Syntax | -Description | -
---|---|
Example | |
void format(char_type*) |
-Set the format for dates. | -
date_input_facet* f = - new date_input_facet(); -f->format("%m %d %Y"); | |
void set_iso_format() |
-Sets the date format to ISO | -
f->set_iso_format(); -// "%Y%m%d" | |
void set_iso_extended_format() |
-Sets the date format to ISO Extended | -
f->set_iso_extended_format(); -// "%Y-%m-%d" | |
void month_format(char_type*) |
-Set the format when 'get'ing months individually. | -
f->month_format("%B"); -ss.str("March"); -ss >> m; // March | |
void weekday_format(char_type*) |
-Set the format when 'get'ing weekdays individually. | -
f->weekday_format("%a"); -ss.str("Sun"); -ss >> wd; // Sunday | |
void year_format(char_type*) |
-Set the format when 'get'ing years individually. | -
f->weekday_format("%y"); -ss.str("04"); -ss >> year; // 2004 | |
void period_parser(...) - Parameter: - period_parser_type |
-Replaces the period parser object with a user created one. | -
see the tutorial for a complete example. | |
void special_values_parser(...) - Parameter: - special_values_parser_type |
-Replaces the special_values parser object with a user created one. | -
see the tutorial for a complete example. | |
void date_gen_phrase_strings(...) - Parameters: - input_collection_type |
-Sets new date generator phrase strings in date_gen_parser. The input collection is a vector of strings (for details on these strings see date generator formatter/parser documentation). | -
void short_weekday_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'getting' short weekdays. | -
see the tutorial for a complete example. | |
void long_weekday_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'getting' long weekdays. | -
see the tutorial for a complete example. | |
void short_month_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'getting' short months. | -
see the tutorial for a complete example. | |
void long_month_names(...) - Parameter: - input_collection_type |
-Replace strings used when 'getting' long months. | -
see the tutorial for a complete example. | |
InItrT get(...) - Common parameters for all - 'get' functions: - InItrT from - InItrT to - ios_base - Unique parameter for 'get' funcs: - gregorian object |
-There are 13 get functions in the date_input_facet. The common parameters are: an iterator pointing to the begining of the stream, an iterator pointing to the end of the stream, and an ios_base object. Each unique gregorian object has it's own get function. Each unique get function is described below. | -
InItrT get(..., date) |
-Gets a date object from the stream using the format set by format(...) or the default. |
-
ss.str("2005-Jan-01"); -ss >> d; // default format | |
InItrT get(..., month) |
-Gets a month object from the stream using the format set by month_format(...) or the default. |
-
ss.str("Feb"); -ss >> m; // default format | |
InItrT get(..., day_of_week) |
-Gets a day of week object from the stream using the format set by weekday_format(...) or the default. |
-
ss.str("Sun"); -ss >> dow; // default format | |
InItrT get(..., day) |
-Gets a day of month object from the stream as a two digit number. | -
"01" // January 1st | |
InItrT get(..., year) |
-Gets a year object from the stream as a number. The number of expected digits depends on the year format. | -
ss/str("2005"); -ss >> y; // default format | |
InItrT get(..., days) |
-Gets a days object from the stream as a number. | -
ss.str("356"); -ss >> dys; // a full year | |
InItrT get(..., date_period) |
-Gets a date_period from the stream. The format of the dates will use the format set by format(..) or the default date format. The type of period (open or closed range) and the delimiters used are those used by the period_parser. |
-
see the tutorial for a complete example. | |
InItrT get(..., partial_date) |
-Gets a partial_date date_generator object from the stream. The month format used is set by month_format(..) or the default. The day of month is represented as a two digit number. |
-
"01 Jan" // default formats -"01 January" // long month format | |
InItrT get(..., date_generator) - Date Generator Type: - nth_day_of_the_week_in_month |
-Gets a nth_day_of_the_week_in_month object from the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_parser. |
-
"third Fri in May" // defaults | |
InItrT get(..., date_generator) - Date Generator Type: - first_day_of_the_week_in_month |
-Gets a first_day_of_the_week_in_month object from the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_parser. |
-
"first Wed of Jun" // defaults | |
InItrT get(..., date_generator) - Date Generator Type: - last_day_of_the_week_in_month |
-Gets a last_day_of_the_week_in_month object from the stream. The month format is set by month_format(...) or the default. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_parser. |
-
"last Tue of Mar" // defaults | |
InItrT get(..., date_generator) - Date Generator Type: - first_day_of_the_week_after |
-Gets a first_day_of_the_week_after object from the stream. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_parser. |
-
"first Sat after" // defaults | |
InItrT get(..., date_generator) - Date Generator Type: - first_day_of_the_week_before |
-Gets a first_day_of_the_week_before object from the stream. The weekday format is set by weekday_format(...) or the default. The remaining phrase elements are set in the date_generator_parser. |
-
"first Mon before" // defaults |
The boost::date_time::time_facet
is an extension of the boost::date_time::date_facet
. The time_facet is typedef'ed in the posix_time
namespace as time_facet
and wtime_facet
. It is typedef'd in the local_time
namespace as local_time_facet
and wlocal_time_facet
.
-
Syntax | -Description | -
---|---|
time_facet() |
-Default constructor | -
time_facet(...) - Parameters: - char_type* format - period_formatter_type - special_values_formatter_type - date_gen_formatter_type |
-Format given will be used for time output. The remaining parameters are formatter objects. Further details on these objects can be found here. This constructor also provides default arguments for all parameters except the format. Therefore, time_facet("%H:%M:S %m %d %Y") will work. |
-
- The time_facet inherits all the public date_facet methods. Therefore, the date_facet methods are not listed here. Instead, they can be found by following this link. -
-Syntax | -Description | -
---|---|
Example | |
void time_duration_format(...) - Parameter: - char_type* |
-Sets the time_duration format. The time_duration format has the ability to display the sign of the duration. The '%+' flag will always display the sign. The '%-' will only display if the sign is negative. Currently the '-' and '+' characters are used to denote the sign. |
-
f->time_duration_format("%+%H:%M"); -// hours and minutes only w/ sign always displayed -time_duration td1(3, 15, 56); -time_duration td2(-12, 25, 32); -ss << td1; // "+03:15:56" -ss << td2; // "-12:25:56" - | |
void set_iso_format() |
-Sets the date and time format to ISO. | -
f->set_iso_format(); -// "%Y%m%dT%H%M%S%F%q" | |
void set_iso_extended_format() |
-Sets the date and time format to ISO Extended | -
f->set_iso_extended_format(); -// "%Y-%m-%d %H:%M:%S%F%Q" | |
OutItrT put(...) - Common parameters for all - 'put' functions: - OutItrT - ios_base - char_type - Unique parameter for 'put' funcs: - posix_time object |
-There are 3 put functions in the time_facet. The common parameters are: an iterator pointing to the next item in the stream, an ios_base object, and the fill character. Each unique posix_time object has it's own put function. Each unique put function is described below. | -
OutItrT put(..., ptime) |
-Puts a ptime object into the stream using the format set by format(...) or the default. |
-
OutItrT put(..., time_duration) |
-Puts a time_duration object into the stream using the format set by time_duration_format(...) or the default. |
-
OutItrT put(..., time_period) |
-Puts a time_period into the stream. The format of the dates and times will use the format set by format(..) or the default date/time format. The type of period (open or closed range) and the delimiters used are those used by the period_formatter. |
-
The boost::date_time::time_input_facet
is an extension of the date_input_facet
. It is typedef'ed in the boost::posix_time
namespace as time_input_facet
and wtime_input_facet
. It is typedef'ed in the boost::local_time
namespace as local_time_input_facet
and wlocal_time_input_facet
.
-
Syntax | -Description | -
---|---|
time_input_facet() |
-Default constructor | -
time_input_facet(string_type) |
-Format given will be used for date/time input. All other formats will use their defaults. | -
time_input_facet(...) - Parameters: - string_type format - format_date_parser_type - special_values_parser_type - period_parser_type - date_gen_parser_type |
-Format given will be used for date/time input. The remaining parameters are parser objects. Further details on these objects can be found here. | -
- The time_input_facet inherits all the public date_input_facet methods. Therefore, the date_input_facet methods are not listed here. Instead, they can be found by following this link. -
-Syntax | -Description | -
---|---|
Example | |
void set_iso_format() |
-Sets the time format to ISO | -
f->set_iso_format(); -// "%Y%m%dT%H%M%S%F%q" -"20051225T132536.789-0700" | |
void set_iso_extended_format() |
-Sets the date format to ISO Extended | -
f->set_iso_extended_format(); -// "%Y-%m-%d %H:%M:%S%F %Q" -"2005-12-25 13:25:36.789 -07:00" | |
void time_duration_format(...) - Parameter: - char_type* |
-Sets the time_duration format. | -
f->time_duration_format("%H:%M"); -// hours and minutes only | |
InItrT get(...) - Common parameters for all - 'get' functions: - InItrT from - InItrT to - ios_base - Unique parameter for 'get' funcs: - gregorian object |
-There are 3 get functions in the time_input_facet. The common parameters are: an iterator pointing to the begining of the stream, an iterator pointing to the end of the stream, and an ios_base object. Each unique gregorian object has it's own get function. Each unique get function is described below. | -
InItrT get(..., ptime) |
-Gets a ptime object from the stream using the format set by format(...) or the default. |
-
ss.str("2005-Jan-01 13:12:01"); -ss >> pt; // default format | |
InItrT get(..., time_duration) |
-Gets a time_duration object from the stream using the format set by time_duration_format(...) or the default. |
-
ss.str("01:25:15.000123000"); -ss >> td; // default format | |
InItrT get(..., time_period) |
-Gets a time_period from the stream. The format of the dates/times will use the format set by format(..) or the default date and time format. The type of period (open or closed range) and the delimiters used are those used by the period_parser. |
-
see the tutorial for a complete example. |
The period_formatter and period_parser provide a uniform interface for the input and output of date_periods, time_periods, and in a future release, local_date_time_periods. The user has control over the delimiters, formats of the date/time components, and the form the period takes. The format of the date/time components is controlled via the date_time input and output facets.
-Periods are constructed with open ranged parameters. The first value is the starting point, and is included in the period. The end value is not included but immediately follows the last value: [begin/end). However, a period can be streamed as either an open range or a closed range.
-[2003-Jan-01/2003-Dec-31] <-- period holding 365 days -[2003-Jan-01/2004-Jan-01) <-- period holding 365 days-
There are four delimiters. The default values are
-"\" - separator |
"[" - start delimiter |
")" - open range end delimiter |
"]" - closed range end delimiter |
A user can provide a custom set of delimiters. Custom delimiters may contain spaces.
-The period form and delimiters can be set as construction parameters or by means of accessor functions. A custom period parser/formatter can then be used as a construction parameter to a new facet, or can be set in an existing facet via an accessor function.
-Period Formatter Doxygen Reference
and here: Period Parser Doxygen Reference
Syntax | -Description | -
---|---|
period_formatter(...) - Parameters: - range_display_options - char_type* - char_type* - char_type* - char_type* |
-NOTE: All five construction parameters have default values so this constructor also doubles as the default constructor. The range_display_options is a public type enum of the period_formatter class. The possible choices are AS_OPEN_RANGE or AS_CLOSED_RANGE. The closed range is the default. A period has three significant points: the begining, the last, and the end. A closed range period takes the form [begin,end), where an open range period takes the form [begin,last]. The four char_type* parameters are: the period separator, the start delimiter, the open range end delimiter, and the closed range end delimiter. |
-
Syntax | -Description | -
---|---|
Example | |
range_display_options range_option() |
-Returns the current setting for the range display (either AS_OPEN_RANGE or AS_CLOSED_RANGE). | -
void range_option(...) - Parameter: - range_display_options |
-Sets the option for range display (either AS_OPEN_RANGE or AS_CLOSED_RANGE). | -
void delimiter_strings(...) - Parameters: - string_type - string_type - string_type - string_type |
-Set new delimiter strings in the formatter. | -
string beg("->| "); -string sep(" || "); -string opn(" ->|"); -string clo(" |<-"); -pf.delimiter_strings(beg, sep, - opn, clo); | |
put_period_start_delimeter(...) - Return Type: - OutItrT - Parameter: - OutItrT |
-Puts the start delimiter into the stream at position pointed to by OutItrT parameter. | -
put_period_sepatator(...) - Return Type: - OutItrT - Parameter: - OutItrT |
-Puts the separator into the stream at position pointed to by OutItrT parameter. | -
put_period_end_delimeter(...) - Return Type: - OutItrT - Parameter: - OutItrT |
-Puts the end delimiter into the stream at position pointed to by OutItrT parameter. | -
OutItrT put_period(...) - Parameters: - OutItrT - ios_base - char_type - period_type - facet_type |
-Puts a period into the stream using the set values for delimiters, separator, and range display. The facet parameter is used to put the date (or time) objects of the period. | -
Syntax | -Description | -
---|---|
period_parser(...) - Parameters: - period_range_option - char_type* - char_type* - char_type* - char_type* |
-NOTE: All five construction parameters have default values so this constructor also doubles as the default constructor. The period_range_option is a public type enum of the period_parser class. The possible choices are AS_OPEN_RANGE or AS_CLOSED_RANGE. The closed range is the default. A period has three significant points: the begining, the last, and the end. A closed range period takes the form [begin,end), where an open range period takes the form [begin,last]. The four char_type* parameters are: the period separator, the start delimiter, the open range end delimiter, and the closed range end delimiter. |
-
period_parser(period_parser) |
-Copy constructor | -
Syntax | -Description | -
---|---|
Example | |
period_range_option range_option() |
-Returns the current setting for the period range (either AS_OPEN_RANGE or AS_CLOSED_RANGE). | -
void range_option(...) - Parameter: - period_range_option |
-Sets the option for period range (either AS_OPEN_RANGE or AS_CLOSED_RANGE). | -
void delimiter_strings(...) - Parameters: - string_type - string_type - string_type - string_type |
-Set new delimiter strings in the parser. | -
string beg("->| "); -string sep(" || "); -string opn(" ->|"); -string clo(" |<-"); -pp.delimiter_strings(beg, sep, - opn, clo); | |
collection_type delimiter_strings() |
-Returns the set of delimiter strings currently held in the parser. | -
period_type get_period(...) - Parameters: - stream_itr_type - stream_itr_type - ios_base - period_type - duration_type - facet_type |
-Parses a period from the stream. The iterator parameters point to the begining and end of the stream. The duration_type is relevant to the period type, for example: A date_period would use days as a duration_type. The period will be parsed according to the formats and strings found in the facet parameter. |
-
_____________________________________________________
-The date_generator formatter and parser provide flexibility by allowing the user to use custom "phrase elements". These phrase elements are the "in-between" words in the date_generators. For example, in the date_generator "Second Monday of March", "Second" and "of" are the phrase elements, where "Monday" and "March" are the date elements. Customization of the date elements is done with the facet. The order of the date and phrase elements cannot be changed. When parsing, all elements of the date_generator phrase must parse correctly or an ios_base::failure exception will be thrown.
-The default "phrase_strings" are: -
-"first" | -"second" | -"third" | -"fourth" | -"fifth" | -"last" | -"before" | -"after" | -"of" | -
- A custom set of phrase_strings must maintain this order of occurance (Ex: "1st", "2nd", "3rd", "4th", "5th", "last", "prior", "past", "in").
-Examples using default phrase_strings and default facet formats for weekday & month:
-"first Tue of Mar"-
And using custom phrase_strings:
-"1st Tue in Mar"-
The custom set of phrase elements can be set as construction parameters or through an accessor function.A custom date_generator parser/formatter can then be used as a construction parameter to a new facet, or can be set in an existing facet via an accessor function.
-IMPORTANT NOTE: Prior to 1.33, partial_date was output as "1 Jan" with a single *or* double digit number for the day. The new behavior is to *always* place a double digit number for the day - "01 Jan".
-Date Generator Formatter Doxygen Reference
and here: Date Generator Parser Doxygen Reference
Syntax | -Description | -
---|---|
date_generator_formatter() |
-Uses the default date generator elements. | -
date_generator_formatter(...) - Parameters: - string_type first_element - string_type second_element - string_type third_element - string_type fourth_element - string_type fifth_element - string_type last_element - string_type before_element - string_type after_element - string_type of_element |
-Constructs a date_generator_formatter using the given element strings. | -
Syntax | -Description | -
---|---|
Example | |
void elements(...) - Parameters: - collection_type - phrase_elements |
-Replace the current phrase elements with a collection of new ones. The phrase_elements parameter is an enum that indicates what the first element in the new collection is (defaults to first). |
-
// col is a collection holding -// "final", "prior", "following", -// and "in" -typedef date_generator_formatter dgf; -dgf formatter(); -formatter.elements(col, dgf::last); -// complete elements in dgf are now: -"first", "second", "third", -"fourth", "fifth", "final", -"prior", "following", and "in" | |
put_partial_date(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - partial_date - facet_type |
-A put function for partial_date. This is a templated function that takes a facet_type as a parameter. | -
Put a partial_date => "dd Month". | |
put_nth_kday(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - nth_kday_type - facet_type |
-A put function for nth_kday_type. This is a templated function that takes a facet_type as a parameter. | -
Put an nth_day_of_the_week_in_month => "nth weekday of month". | |
put_first_kday(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - first_kday_type - facet_type |
-A put function for first_kday_type. This is a templated function that takes a facet_type as a parameter. | -
Put a first_day_of_the_week_in_month => "first weekday of month". | |
put_last_kday(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - last_kday_type - facet_type |
-A put function for last_kday_type. This is a templated function that takes a facet_type as a parameter. | -
Put a last_day_of_the_week_in_month => "last weekday of month". | |
put_kday_before(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - kday_before_type - facet_type |
-A put function for kday_before_type. This is a templated function that takes a facet_type as a parameter. | -
Put a first_day_of_the_week_before => "weekday before" | |
put_kday_after(...) - Return Type: - facet_type::OutItrT - Parameters: - OutItrT next - ios_base - char_type fill - kday_after_type - facet_type |
-A put function for kday_after_type. This is a templated function that takes a facet_type as a parameter. | -
Put a first_day_of_the_week_after => "weekday after". |
Syntax | -Description | -
---|---|
date_generator_parser() |
-Uses the default date generator elements. | -
date_generator_parser(...) - Parameter: - date_generator_parser |
-Copy Constructor | -
date_generator_parser(...) - Parameters: - string_type first_element - string_type second_element - string_type third_element - string_type fourth_element - string_type fifth_element - string_type last_element - string_type before_element - string_type after_element - string_type of_element |
-Constructs a date_generator_parser using the given element strings. | -
Syntax | -Description | -
---|---|
Example | |
void element_strings(...) - Parameter: - collection_type |
-Replace the set of date generator element string with a new set. | -
void element_strings(...) - Parameters: - string_type first - string_type second - string_type third - string_type fourth - string_type fifth - string_type last - string_type before - string_type after - string_type of |
-Replace the set of date generator elements with new values. | -
get_partial_date_type(...) - Return Type: - facet_type::partial_date_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses a partial_date => "dd Month". | |
get_nth_kday_type(...) - Return Type: - facet_type::nth_kday_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses an nth_day_of_the_week_in_month => "nth weekday of month". | |
get_first_kday_type(...) - Return Type: - facet_type::firat_kday_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses a first_day_of_the_week_in_month => "first weekday of month". | |
get_last_kday_type(...) - Return Type: - facet_type::last_kday_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses a last_day_of_the_week_in_month => "last weekday of month". | |
get_kday_before_type(...) - Return Type: - facet_type::kday_before_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses a first_day_of_the_week_before => "weekday before" | |
get_kday_after_type(...) - Return Type: - facet_type::kday_after_type - Parameters: - stream_itr_type next - stream_itr_type str_end - ios_base - facet_type |
-A templated function that parses a date_generator from the stream. | -
Parses a first_day_of_the_week_after => "weekday after". |
_____________________________________________________
-The date_time library uses five special_values. They are: -
-not_a_date_time | -neg_infin | -pos_infin | -min_date_time | -max_date_time | -
The default set of strings used to represent these types are: "not-a-date-time", "-infinity", "+infinity", "minimum-date-time", "maximum-date-time". When output, the min_date-time and max_date_time appear as normal date/time representations: "1400-Jan-01" and "9999-Dec-31" repectively.
-The special values parser/formatter allows the user to set custom strings for these special values. These strings can be set as construction parameters to a new facet, or can be set in an existing facet via an accessor function.
-Special Values Formatter Doxygen Reference
and here: Special Values Parser Doxygen Reference
Syntax | -Description | -
---|---|
special_values_formatter() |
-Constructor uses defaults for special value strings. | -
special_values_formatter(...) - Parameters: - collection_type::iterator - collection_type::iterator |
-Constructs using values in collection. NOTE: Only the first three strings of the collection will be used. Strings for minimum_date_time and maximum_date_time are ignored as those special values are output as normal dates/times. | -
special_values_formatter(...) - Parameters: - char_type* - char_type* |
-Constructs special values formatter from an array of strings. | -
Syntax | -Description | -
---|---|
Example | |
OutItrT put_special(...) - Parameters: - OutItrT next - special_values value |
-Puts the given special value into the stream. | -
date d1(not_a_date_time); -date d2(minimum_date_time); -special_values_formatter formatter; -formatter.put_special(itr, d1); -// Puts: "not-a-date-time" -formatter.put_special(itr, d2); -// Puts: "1400-Jan-01" |
Syntax | -Description | -
---|---|
special_values_parser() |
-- |
special_values_parser(...) - Parameters: - collection_type::iterator - collection_type::iterator |
-Constructs a special values parser using the strings in the collection. | -
special_values_parser(...) - Parameter: - scpecial_values_parser |
-Copy constructor. | -
special_values_parser(...) - Parameters: - string_type nadt_str - string_type neg_inf_str - string_type pos_inf_str - string_type min_dt_str - string_type max_dt_str |
-Constructs a special values parser using the supplied strings. | -
Syntax | -Description | -
---|---|
Example | |
void sv_strings(...) - Parameters: - string_type nadt_str - string_type neg_inf_str - string_type pos_inf_str - string_type min_dt_str - string_type max_dt_str |
-Replace the set of special value strings with the given ones. | -
bool match(...) - Parameters: - stream_itr_type beg - stream_itr_type end - match_results |
-Returns true if parse was successful. Upon a successful parse, mr.current_match will be set an int values corresponding to the equivalent special_value. |
-
// stream holds "maximum_date_time" -typedef special_values_parser svp; -svp parser; -svp::match_results mr; -if(parser.match(itr, str_end, mr)) { - d = date(static_cast<special_values>( - mr.match_results)) -} else { - // error, failed parse -} -// d == "9999-Dec-31" |
_____________________________________________________
-The format date parser is the object that holds the strings for months and weekday names, as well as their abbreviations. Custom sets of strings can be set at construction time, or, the strings in an existing format_date_parser can be replaced through accessor functions. Both the constructor and the accessor functions take a vector of strings as their arguments.
-Doxygen Reference
Syntax | -Description | -
---|---|
format_date_parser(...) - Parameters: - string_type format - std::locale |
-Creates a parser that uses the given format for parsing dates (in those functions where there is no format parameter). The names and abbreviations used are extracted from the given locale. | -
format_date_parser(...) - Parameters: - string_type format - input_collection_type - input_collection_type - input_collection_type - input_collection_type |
-Creates a parser from using the given components. The input_collection_type parameters are for: short month names, long month names, short weekday names, and long weekday names (in that order). These collections must contain values for every month and every weekday (begining with January and Sunday). | -
format_date_parser(...) - Parameters: - format_date_parser |
-Copy Constructor | -
Syntax | -Description | -
---|---|
Example | |
string_type format() |
-Returns the format that will be used when parsing dates in those functions where there is no format parameter. | -
void format(string_type) |
-Sets the format that will be used when parsing dates in those functions where there is no format parameter. | -
void short_month_names(...) - Parameter: - input_collection_type names |
-Replace the short month names used by the parser. The collection must contain values for each month, starting with January. | -
void long_month_names(...) - Parameter: - input_collection_type names |
-Replace the long month names used by the parser. The collection must contain values for each month, starting with January. | -
void short_weekday_names(...) - Parameter: - input_collection_type names |
-Replace the short weekday names used by the parser. The collection must contain values for each weekday, starting with Sunday. | -
void long_weekday_names(...) - Parameter: - input_collection_type names |
-Replace the long weekday names used by the parser. The collection must contain values for each weekday, starting with Sunday. | -
date_type parse_date(...) - Parameters: - string_type input - string_type format - special_values_parser |
-Parse a date from the given input using the given format. | -
string inp("2005-Apr-15"); -string format("%Y-%b-%d"); -date d; -d = parser.parse_date(inp, - format, - svp); -// d == 2005-Apr-15 | |
date_type parse_date(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end - special_values_parser |
-Parse a date from stream using the parser's format. | -
date_type parse_date(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end - string_type format - special_values_parser |
-Parse a date from stream using the given format. | -
// stream holds "2005-04-15" -string format("%Y-%m-%d"); -date d; -d = parser.parse_date(itr, - str_end, - format, - svp); -// d == 2005-Apr-15 | |
month_type parse_month(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end - string_type format |
-Parses a month from stream using given format. Throws bad_month if unable to parse. | -
// stream holds "March" -string format("%B"); -greg_month m; -m = parser.parse_month(itr, - str_end, - format); -// m == March | |
day_type parse_day_of_the_month(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end |
-Parses a day from stream. The day must appear as a number (1-31) or a bad_day_of_month will be thrown. | -
// stream holds "01" -greg_day d; -d = parser.parse_day_of_month(itr, - str_end); -// d == 1st | |
day_of_week_type parse_weekday(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end - string_type format |
-Parse a weekday from stream according to the given format. Throws a bad_weekday if unable to parse. | -
// stream holds "Tue" -string format("%a"); -greg_weekday wd; -wd = parser.parse_weekday(itr, - str_end, - format); -// wd == Tuesday | |
year_type parse_year(...) - Parameters: - istreambuf_iterator input - istreambuf_iterator str_end - string_type format |
-Parse a year from stream according to given format. Throws bad year if unable to parse. | -
// stream holds "98" -string format("%y"); -greg_year y; -y = parser.parse_year(itr, - str_end, - format); -// y == 1998 |
Facets are automatically imbued when operators '>>' and '<<' are called. The list of date_time objects that can be streamed are:
-date
,
- days
,
- date_period
,
- greg_month
,
- greg_weekday
,
- greg_year
,
- partial_date
,
- nth_day_of_the_week_in_month
,
- first_day_of_the_week_in_month
,
- last_day_of_the_week_in_month
,
- first_day_of_the_week_after
,
- first_day_of_the_week_before
ptime
,
- time_period
,
- time_duration
local_date_time
- The following example is of the basic use of the new IO code, utilizing all the defaults. (this example can be found in the libs/date_time/examples/tutorial
directory)
-
- date d(2004, Feb, 29); - time_duration td(12,34,56,789); - stringstream ss; - ss << d << ' ' << td; - ptime pt(not_a_date_time); - cout << pt << endl; // "not-a-date-time" - ss >> pt; - cout << pt << endl; // "2004-Feb-29 12:34:56.000789" - ss.str(""); - ss << pt << " EDT-05EDT,M4.1.0,M10.5.0"; - local_date_time ldt(not_a_date_time); - ss >> ldt; - cout << ldt << endl; // "2004-Feb-29 12:34:56.000789 EDT" --
This example used the default settings for the input and output facets. The default formats are such that interoperability like that shown in the example is possible. NOTE: Input streaming of local_date_time can only be done with a posix time zone string. The default output format uses a time zone abbreviation. The format can be changed so out and in match (as we will see later in this tutorial).
-The format strings control the order, type, and style of the date/time elements used. The facets provide some predefined formats (iso_format_specifier, iso_format_extended_specifier, and default_date_format) but the user can easily create their own.
- (continued from previous example) -- local_time_facet* output_facet = new local_time_facet(); - local_time_input_facet* input_facet = new local_time_input_facet(); - ss.imbue(locale(locale::classic(), output_facet)); - ss.imbue(locale(ss.getloc(), input_facet)); - - output_facet->format("%a %b %d, %H:%M %z"); - ss.str(""); - ss << ldt; - cout << ss.str() << endl; // "Sun Feb 29, 12:34 EDT" - - output_facet->format(local_time_facet::iso_time_format_specifier); - ss.str(""); - ss << ldt; - cout << ss.str() << endl; // "20040229T123456.000789-0500" - - output_facet->format(local_time_facet::iso_time_format_extended_specifier); - ss.str(""); - ss << ldt; - cout << ss.str() << endl; // "2004-02-29 12:34:56.000789-05:00" --
Format strings are not limited to date/time elements. Extra verbiage can be placed in a format string. NOTE: When extra verbiage is present in an input format, the data being input must also contain the exact verbiage.
- (continued from previous example) -- // extra words in format - string my_format("The extended ordinal time %Y-%jT%H:%M can also be \ - represented as %A %B %d, %Y"); - output_facet->format(my_format.c_str()); - input_facet->format(my_format.c_str()); - ss.str(""); - ss << ldt; - cout << ss.str() << endl; - - // matching extra words in input - ss.str("The extended ordinal time 2005-128T12:15 can also be \ - represented as Sunday May 08, 2005"); - ss >> ldt; - cout << ldt << endl; --
So far we've shown how a user can achieve a great deal of customization with very little effort by using formats. Further customization can be achieved through user defined elements (ie strings). The elements that can be customized are: Special value names, month names, month abbreviations, weekday names, weekday abbreviations, delimiters of the date/time periods, and the phrase elements of the date_generators.
-The default values for these are as follows:
-not-a-date-time
,
- -infinity
,
- +infinity
,
- minimum-date-time
,
- maximum-date-time
English calendar and three letter abbreviations
English calendar and three letter abbreviations
first
,
- second
,
- third
,
- fourth
,
- fifth
,
- last
,
- before
,
- after
,
- of
NOTE: We've shown earlier that the components of a date/time representation can be re-ordered via the format string. This is not the case with date_generators. The elements themselves can be customized but their order cannot be changed.
-To illustrate the customization possibilities we will use custom strings for months and weekdays (we will only use long names, is all lowercase, for this example).
- (continued from previous example) -- // set up the collections of custom strings. - // only the full names are altered for the sake of brevity - string month_names[12] = { "january", "february", "march", - "april", "may", "june", - "july", "august", "september", - "october", "november", "december" }; - vector<string> long_months(&month_names[0], &month_names[12]); - string day_names[7] = { "sunday", "monday", "tuesday", "wednesday", - "thursday", "friday", "saturday" }; - vector<string> long_days(&day_names[0], &day_names[7]); - - // create date_facet and date_input_facet using all defaults - date_facet* date_output = new date_facet(); - date_input_facet* date_input = new date_input_facet(); - ss.imbue(locale(ss.getloc(), date_output)); - ss.imbue(locale(ss.getloc(), date_input)); - - // replace names in the output facet - date_output->long_month_names(long_months); - date_output->long_weekday_names(long_days); - - // replace names in the input facet - date_input->long_month_names(long_months); - date_input->long_weekday_names(long_days); - - // customize month, weekday and date formats - date_output->format("%Y-%B-%d"); - date_input->format("%Y-%B-%d"); - date_output->month_format("%B"); // full name - date_input->month_format("%B"); // full name - date_output->weekday_format("%A"); // full name - date_input->weekday_format("%A"); // full name - - ss.str(""); - ss << greg_month(3); - cout << ss.str() << endl; // "march" - ss.str(""); - ss << greg_weekday(3); - cout << ss.str() << endl; // "tuesday" - ss.str(""); - ss << date(2005,Jul,4); - cout << ss.str() << endl; // "2005-july-04" --
Customizing the input and output of special values is best done by creating a new special_values_parser and special_values_formatter. The new strings can be set at construction time (as in the example below).
- (continued from previous example) -- // reset the formats to defaults - output_facet->format(local_time_facet::default_time_format); - input_facet->format(local_time_input_facet::default_time_input_format); - - // create custom special_values parser and formatter objects - // and add them to the facets - string sv[5] = {"nadt","neg_inf", "pos_inf", "min_dt", "max_dt" }; - vector<string> sv_names(&sv[0], &sv[5]); - special_values_parser sv_parser(sv_names.begin(), sv_names.end()); - special_values_formatter sv_formatter(sv_names.begin(), sv_names.end()); - output_facet->special_values_formatter(sv_formatter); - input_facet->special_values_parser(sv_parser); - - ss.str(""); - ldt = local_date_time(not_a_date_time); - ss << ldt; - cout << ss.str() << endl; // "nadt" - - ss.str("min_dt"); - ss >> ldt; - ss.str(""); - ss << ldt; - cout << ss.str() << endl; // "1400-Jan-01 00:00:00 UTC" --
NOTE: even though we sent in strings for min and max to the formatter, they are ignored because those special values construct to actual dates (as shown above).
-Customizing the input and output of periods is best done by creating a new period_parser and period_formatter. The new strings can be set at construction time (as in the example below).
- (continued from previous example) -- // all formats set back to defaults (not shown for brevity) - - // create our date_period - date_period dp(date(2005,Mar,1), days(31)); // month of march - - // custom period formatter and parser - period_formatter per_formatter(period_formatter::AS_OPEN_RANGE, - " to ", "from ", " exclusive", " inclusive" ); - period_parser per_parser(period_parser::AS_OPEN_RANGE, - " to ", "from ", " exclusive" , "inclusive" ); - - // default output - ss.str(""); - ss << dp; - cout << ss.str() << endl; // "[2005-Mar-01/2005-Mar-31]" - - // add out custom parser and formatter to the facets - date_output->period_formatter(per_formatter); - date_input->period_parser(per_parser); - - // custom output - ss.str(""); - ss << dp; - cout << ss.str() << endl; // "from 2005-Feb-01 to 2005-Apr-01 exclusive" --
Customizing the input and output of date_generators is done by replacing the existing strings (in the facet) with new strings.
-NOTE: We've shown earlier that the components of a date/time representation can be re-ordered via the format string. This is not the case with date_generators. The elements themselves can be customized but their order cannot be changed.
- (continued from previous example) -- // custom date_generator phrases - string dg_phrases[9] = { "1st", "2nd", "3rd", "4th", "5th", - "final", "prior to", "following", "in" }; - vector<string> phrases(&dg_phrases[0], &dg_phrases[9]); - - // create our date_generator - first_day_of_the_week_before d_gen(Monday); - - // default output - ss.str(""); - ss << d_gen; - cout << ss.str() << endl; // "Mon before" - - // add our custom strings to the date facets - date_output->date_gen_phrase_strings(phrases); - date_input->date_gen_element_strings(phrases); - - // custom output - ss.str(""); - ss << d_gen; - cout << ss.str() << endl; // "Mon prior to" --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Timepoints -- - Durations -- - Intervals (Periods) -- - Special Value Handling
-- 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 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) --
- 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 --
- 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(∞) --
Category | -Description | -
---|---|
Functions | |
Interfaces | -Provide concrete classes for manipulation of dates and times | -
| |
Calculation | -Provide a basis for performing efficient time calculations | -
| |
Representation Flexibility | -Provide the maximum possible reusability and flexibility | -
| |
Date Calculations | -Provide tools for date calculations | -
| |
Time Calculations | -Provide concrete classes for manipulation of time | -
| |
Clock Interfaces | -Provide classes for retrieving time current time | -
| |
I/O Interfaces | -Provide input and output for time including | -
|
- 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: -
-- 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. -
-- 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. -
-- 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. -
-- 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: -
-- 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. -
-- Predictable types have a couple of important properties: -
-- 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: -
-- 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. -
-- 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. -
-- The following are a number of terms relevant to the date-time domain. -
-- A taxonomy of temporal types: -
-- And some other terms: -
-- Some standard date-time terminology: -
-- Some more experimental ones: -
-- These are design sorts of terms: -
-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. -
-Overview -- - Compilation Options -- - Compiler/Portability Notes -- - Directory Structure -- - Required Boost Libraries
-- 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. -
-- By default the posix_time system uses a single 64 bit integer internally to provide a microsecond level resolution. As an alternative, a combination of a 64 bit integer and a 32 bit integer (96 bit resolution) can be used to provide nano-second level resolutions. The default 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 (96 bit nanosecond) 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.
-
As of version 1.33, the date_time library introduced a new IO streaming system. Some compilers are not capable of utilizing this new system. For those compilers the earlier ("legacy") IO system is still available. Non-supported compilers will select the legacy system automatically but the user can force the usage of the legacy system by defining USE_DATE_TIME_PRE_1_33_FACET_IO
.
As a convenience, date_time
has provided some additional duration types. Use of these types may have unexpected results due to the snap-to-end-of-month behavior (see Reversibility of Operations Pitfall for complete details and examples). These types are enabled by default. To disable these types, simply undefine BOOST_DATE_TIME_OPTIONAL_GREGORIAN_TYPES
in your project file.
Another convenience is the default constructors for date
, and ptime
. These constructors are enabled by default. To disable them, simply define DATE_TIME_NO_DEFAULT_CONSTRUCTOR
in your project file.
- 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: -
-
- * These compilers do not support the wstring/wstream
aspects of the date_time
library.
-
- 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. Some compilers/standard libraries with this limitation include: -
-- Metrowerks Code Warrior 9.4 has some input I/O limitations, but is otherwise - fully supported. -
-There is a known issue with Visual Studio (7.0 & 7.1) and STLPort. The build errors typically make reference to a type issue or 'no acceptable conversion' and are attempting to instantiate a template with wchar_t
. The default build of STLPort does not support wchar_t
. There are two possible workarounds for this issue. The simplest is the user can build date_time with no wide stream/string etc. The other is to rebuild STLPort with wchar_t support.
-
To build date_time with no wide stream/string etc, execute the following command from $BOOST_ROOT
:
-
bjam -a "-sTOOLS=vc-7_1-stlport" "-sSTLPORT_PATH=..." \ - "-sBUILD=<define>BOOST_NO_STD_WSTRING" \ - --stagedir=... --with-date_time stage-
- (replace the ellipsis with the correct paths for the build system and adjust the TOOLS
to the proper toolset if necessary)
-
Rebuilding STLPort with wchar_t
support involves placing /Zc:wchar_t
in the STLPort makefile. Date_time should then be built with the following command from $BOOST_ROOT
:
-
bjam -a "-sTOOLS=vc-7_1-stlport" "-sSTLPORT_PATH=..." \ - "-sBUILD=&native-wchar_t>on" \ - --stagedir=... --with-date_time stage-
- (replace the ellipsis with the correct paths for the build system and adjust the TOOLS
to the proper toolset if necessary)
-
- The directory tree has the following structure: -
-/boost/date_time -- common headers and template code -/boost/date_time/gregorian -- Gregorian date system header files -/boost/date_time/posix_time -- Posix time system headers -/boost/date_time/local_time -- Local 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/test/local_time -- test battery for the local_time system -/libs/date_time/examples/gregorian -- example programs for dates -/libs/date_time/examples/posix_time -- time example programs -/libs/date_time/examples/local_time -- 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...)-
- Various parts of date-time depend on other boost libraries. These include: -
-- so at least these libraries need to be installed. -
-- 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 - libs/date_time/test/local_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. -
-Type | -Description | -
---|---|
Bug Fix | -Period lengths, when beginning and end points are the same, or are consecutive, were being incorrectly calculated. The corrected behavior, where end and beginning points are equal, or a period is created with a zero duration, now return a length of zero. A period where beginning and end points are consecutive will return a length of one. - | -
Bug Fix | -Time_input_facet was missing functions to set iso formats. It also failed to parse time values that did not use a separator (%H%M%S). Both these bugs have been corrected. - | -
Feature | -Preliminary names of ptime_facet and ptime_input_facet changed to simply time_facet and time_input_facet. The ptime_* versions have been removed all together. - | -
Feature | -The from_iso_string function failed to parse fractional digits. We added code that correctly parses when input has more digits, or too few digits, that the compiled library precision. Ptimes with only a decimal are also correctly parsed. - | -
Bug Fix | -The parsing mechanism in the new IO would consume the next character after a match was made. This bug presented itself when attempting to parse a period that had special value for it's beginning point. - | -
Bug Fix | -The new IO system failed to provide the ability for the user to "turn on" exceptions on the stream. The failbit was also not set when parsing failed. Both of these problems have been fixed. - | -
Bug Fix | -Parsing of special values, by means of from_*_string functions, has been fixed. This also effects the libraries ability to serialize special values. Time_duration now serializes as either a string or individual fields (depending on is_special()). - | -
Bug Fix | -Previously, output streaming of partial_date would display the day as either a single or double digit integer (ie '1', or '12'). This has been corrected to always display a double digit integer (ie '01').
- |
-
Feature | -Major new features related to management of local times. - This includes the introduction of a series of new classes to - represent time zones and local times (see Date Time Local Time for complete details). - | -
Feature | -Input and output facets have been re-written to support format-based - redefinition of formats (see Date Time IO for complete details). - | -
Feature | -Functions have been added to facilitate conversions between tm structs for date , ptime , time_duration , and local_date_time . Functions for converting FILETIME , and time_t to ptime are also provided. See the individual sections for details.
- |
-
Feature | -A universal_time function has been added to the microsec_time_clock (full details of this function can be found here).
- |
-
Feature | -Functions have been added to facilitate conversions between tm structs for date , ptime , time_duration , and local_date_time . Functions for converting FILETIME , and time_t to ptime are also provided. See the individual sections for details.
- |
-
Feature | -A universal_time function has been added to the microsec_time_clock (full details of this function can be found here).
- |
-
Feature | -Date-time now uses reentrant POSIX functions on those platforms that - support them when BOOST_HAS_THREADS is defined. - | -
Bug Fix | -Fixed a bug in serialization code where special values - (not-a-date-time, infinities, etc) for - ptime, time_duration would not read back correctly from an archive. - The output serialization code wrote subfields such - as time_duration.seconds() which are invalid for special values and - thus undefined values. Thus when read back the values could cause - strange behavior including execeptions on construction. - | -
Bug Fix | -Fixed multiple warnings generated with various platforms/compilers. - | -
Bug Fix | -Construction of a ptime with a time_duration beyond the range of 00:00 to 23:59:59.9... now adjusts the date and time to make the time_duration fall within this range (ie ptime(date(2005,2,1), hours(-5)) -> "2005-Jan-31 19:00:00" & ptime(date(2005,2,1), hours(35)) -> "2005-Feb-02 11:00:00").
- |
-
Bug Fix | -Time parsing now correctly handles excessive digits for fractional seconds. Leading zeros are dropped ("000100" -> 100 frac_sec), and excessive digits are truncated at the proper place ("123456789876" -> 123456 or 123456789 depending on what precision the library was compiled with). - | -
Bug Fix | -Changes to the boost::serialization interface broke serialization compatibility for date_time . The user must provide a function to insure date_time objects are const before they are serialized. The function should be similar to:
- template<class archive_type, class temporal_type> -void save_to(archive_type& ar, - const temporal_type& tt) -{ - ar << tt; -}- |
-
Bug Fix | -Use of the depricated boost::tokenizer interface has been updated to the current interface. This fixes compiler errors on some older compilers.
- |
-
Bug Fix | -Templatized formatters in the legacy IO system to accept char type. Also removed calls to boost::lexical_cast .
- |
-
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:
-
|
-||||||||||||||||||
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); -ptime 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. - | -
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. | -
- 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. | -
- 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. -
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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. -
-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; - } -}-
Time adjustment calculations based on machine
-namespace boost { - namespace date_time { - template<typename time_type> class c_local_adjustor; - } -}-
Provide workarounds related to the ctime header
-namespace std { -}namespace boost { - namespace date_time { - struct c_time; - } -}-
namespace std {
-}
-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; - - // - enum violation_enum { min_violation, max_violation }; - } -}-
namespace boost { - namespace date_time { - template<typename T, typename calendar, typename duration_type_> class date; - } -}-
namespace boost { - namespace date_time { - template<typename date_type> class day_clock; - } -}-
namespace boost { - namespace date_time { - - // - enum weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, - Saturday }; - - // - enum months_of_year { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, - Nov, Dec, NotAMonth, NumMonths }; - } -}-
namespace boost { - namespace date_time { - template<typename duration_rep_traits> class date_duration; - - struct duration_traits_long; - struct duration_traits_adapted; - } -}-
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; - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > - class date_facet; - template<typename date_type, typename CharT, - typename InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > > - class date_input_facet; - } -}-
namespace boost { - namespace date_time { - template<typename charT> class simple_format; - - template<> class simple_format<wchar_t>; - } -}-
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; - } -}-
namespace boost { - namespace date_time { - } -}-
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; - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > - class date_generator_formatter; - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename charT> class date_generator_parser; - } -}-
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 &); - } -}-
namespace boost { - namespace date_time { - template<typename date_type> class date_itr_base; - template<typename offset_functor, typename date_type> class date_itr; - - // - enum date_resolutions { day, week, months, year, decade, century, - NumDateResolutions }; - } -}-
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; - } -}-
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 }; - } -}-
namespace boost { - namespace date_time { - template<typename date_type> class dst_day_calc_rule; - template<typename spec> class day_calc_dst_rule; - } -}-
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 &); - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename charT> class format_date_parser; - template<typename int_type, typename charT> - int_type fixed_string_to_int(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, - parse_match_result< charT > &, - unsigned int); - template<typename int_type, typename charT> - int_type var_string_to_int(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, - unsigned int); - } -}-
namespace boost { - namespace date_time { - template<typename ymd_type_, typename date_int_type_> - class gregorian_calendar_base; - } -}-
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 > &); - } -}-
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; - } -}-
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(); - } -}-
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; - } -}-
This file contains a high resolution time clock implementation.
-namespace boost { - namespace date_time { - template<typename time_type> class microsec_clock; - } -}-
namespace boost { - namespace date_time { - - // - enum month_format_spec { month_as_integer, month_as_short_string, - month_as_long_string }; - enum ymd_order_spec; - } -}-
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; - } -}-
namespace boost { - namespace date_time { - template<typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > - class period_formatter; - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename CharT> class period_parser; - } -}-
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 }; - } -}-
namespace boost { - namespace date_time { - template<typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > - class special_values_formatter; - } -}-
namespace boost { - namespace date_time { - template<typename date_type, typename charT> class special_values_parser; - } -}-
namespace boost { - namespace date_time { - template<typename InputT, typename OutputT> - std::basic_string< OutputT > - convert_string_type(const std::basic_string< InputT > &); - } -}-
namespace boost { - namespace date_time { - template<typename charT> struct parse_match_result; - template<typename charT> struct string_parse_tree; - template<typename charT> - std::basic_ostream< charT > & - operator<<(std::basic_ostream< charT > & os, - parse_match_result< charT > & mr); - } -}-
namespace boost { - namespace date_time { - template<typename charT> - std::vector< std::basic_string< charT > > - gather_month_strings(const std::locale &, bool = true); - template<typename charT> - std::vector< std::basic_string< charT > > - gather_weekday_strings(const std::locale &, bool = true); - } -}-
This file contains the interface for the time associated classes.
-namespace boost { - namespace date_time { - template<typename T, typename time_system> class base_time; - } -}-
This file contains the interface for clock devices.
-namespace boost { - namespace date_time { - template<typename time_type> class second_clock; - } -}-
This file contains nice definitions for handling the resoluion of various time reprsentations.
-namespace boost { - namespace date_time { - - // - enum time_resolutions { sec, tenth, hundreth, milli, ten_thousandth, - micro, nano, NumResolutions }; - - // - enum dst_flags { not_dst, is_dst, calculate }; - } -}-
namespace boost { - namespace date_time { - template<typename T, typename rep_type> class time_duration; - template<typename base_duration, boost::int64_t frac_of_second> - class subsecond_duration; - } -}-
namespace boost { - namespace date_time { - template<typename CharT> struct time_formats; - - template<typename time_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > - class time_facet; - template<typename time_type, typename CharT, - typename InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > > - class time_input_facet; - } -}-
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; - } -}-
namespace boost { - namespace date_time { - template<typename time_type> class time_itr; - } -}-
namespace boost { - namespace date_time { - - // computes exponential math like 2^8 => 256, only works with positive integers - template<typename int_type> - int_type power(int_type base, int_type exponent); - 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[.fff...] (eg: 120259.123 is 12 hours, 2 min, 59 seconds, 123000 microseconds). - 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); - } -}-
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); - } -}-
namespace boost { - namespace date_time { - template<typename config> struct counted_time_rep; - - template<typename time_rep> class counted_time_system; - } -}-
namespace boost { - namespace date_time { - template<typename config, boost::int32_t ticks_per_second> - class split_timedate_system; - } -}-
namespace boost { - namespace date_time { - template<typename time_type, typename CharT = char> class time_zone_base; - template<typename time_duration_type> class dst_adjustment_offsets; - } -}-
namespace boost { - namespace date_time { - template<typename CharT = char> class time_zone_names_base; - - typedef time_zone_names_base< char > time_zone_names; // Specialization of timezone names for standard char. - } -}-
namespace boost { - namespace date_time { - struct data_not_accessible; - struct bad_field_count; - - template<typename time_zone_type, typename rule_type> class tz_db_base; - } -}-
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; - } -}-
namespace boost { - namespace date_time { - template<typename YearType, typename MonthType, typename DayType> - struct year_month_day_base; - } -}-
namespace boost { - namespace gregorian { - - // Converts a date to a tm struct. Throws out_of_range exception if date is a special value. - tm to_tm(const date & d); - - // Converts a tm structure into a date dropping the any time values. - date date_from_tm(const tm & datetm); - } -}-
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); - } -}-
namespace boost { - namespace gregorian { - } -}-
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. - } -}-
namespace boost { - namespace gregorian { - class date; - } -}-
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. - } -}-
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. - } -}-
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. - } -}-
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; - } -}-
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); - } -}-
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. - } -}-
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; - } -}-
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. - } -}-
namespace boost { - namespace gregorian { - typedef date_time::year_month_day_base< greg_year, greg_month, greg_day > greg_year_month_day; - } -}-
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.
-namespace boost { - namespace gregorian { - typedef boost::date_time::period_formatter< wchar_t > wperiod_formatter; - typedef boost::date_time::period_formatter< char > period_formatter; - typedef boost::date_time::date_facet< date, wchar_t > wdate_facet; - typedef boost::date_time::date_facet< date, char > date_facet; - typedef boost::date_time::period_parser< date, char > period_parser; - typedef boost::date_time::period_parser< date, wchar_t > wperiod_parser; - typedef boost::date_time::special_values_formatter< char > special_values_formatter; - typedef boost::date_time::special_values_formatter< wchar_t > wspecial_values_formatter; - typedef boost::date_time::special_values_parser< date, char > special_values_parser; - typedef boost::date_time::special_values_parser< date, wchar_t > wspecial_values_parser; - typedef boost::date_time::date_input_facet< date, char > date_input_facet; - typedef boost::date_time::date_input_facet< date, wchar_t > wdate_input_facet; - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::date & d); - - // input operator for date - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, date & d); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::date_duration & dd); - - // input operator for date_duration - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, date_duration & dd); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::date_period & dp); - - // input operator for date_period - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, date_period & dp); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::greg_month & gm); - - // input operator for greg_month - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, greg_month & m); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::greg_weekday & gw); - - // input operator for greg_weekday - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, greg_weekday & wd); - - // input operator for greg_day - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, greg_day & gd); - - // input operator for greg_year - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, greg_year & gy); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::partial_date & pd); - - // input operator for partial_date - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, partial_date & pd); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::nth_day_of_the_week_in_month & nkd); - - // input operator for nth_day_of_the_week_in_month - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - nth_day_of_the_week_in_month & nday); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::first_day_of_the_week_in_month & fkd); - - // input operator for first_day_of_the_week_in_month - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - first_day_of_the_week_in_month & fkd); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::last_day_of_the_week_in_month & lkd); - - // input operator for last_day_of_the_week_in_month - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - last_day_of_the_week_in_month & lkd); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::first_day_of_the_week_after & fda); - - // input operator for first_day_of_the_week_after - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - first_day_of_the_week_after & fka); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::gregorian::first_day_of_the_week_before & fdb); - - // input operator for first_day_of_the_week_before - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - first_day_of_the_week_before & fkb); - } -}-
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. - } -}-
namespace boost { - namespace gregorian { - special_values special_value_from_string(const std::string &); - - // 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); - } -}-
namespace boost { - namespace posix_time { - - // Function that converts a time_t into a ptime. - ptime from_time_t(std::time_t t); - - // Convert a time to a tm structure truncating any fractional seconds. - tm to_tm(const boost::posix_time::ptime & t); - - // Convert a time_duration to a tm structure truncating any fractional seconds and zeroing fields for date components. - tm to_tm(const boost::posix_time::time_duration & td); - - // Convert a tm struct to a ptime ignoring is_dst flag. - ptime ptime_from_tm(const tm & timetm); - template<typename time_type> time_type from_ftime(const FILETIME &); - } -}-
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 &); - } -}-
Global header file to get all of posix time types
-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; - } -}-
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; - } -}-
namespace boost { - namespace posix_time { - typedef boost::date_time::time_facet< ptime, wchar_t > wtime_facet; // ptime_input_facet is depricated and will be phased out. use time_input_facet instead - typedef boost::date_time::time_facet< ptime, char > time_facet; - typedef boost::date_time::time_input_facet< ptime, wchar_t > wtime_input_facet; - typedef boost::date_time::time_input_facet< ptime, char > time_input_facet; - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, const ptime & p); - - // input operator for ptime - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, ptime & pt); - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const boost::posix_time::time_period & p); - - // input operator for time_period - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, time_period & tp); - - // 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); - - // input operator for time_duration - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, time_duration & td); - } -}-
namespace boost { - namespace posix_time { - - // 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); - 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 &); - } -}-
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; - } -}-
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 > 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. - } -}-
namespace boost { - namespace posix_time { - class ptime; - } -}-
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); - } -}-
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); - } -}-
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); - } -}-
namespace boost { - namespace posix_time { - typedef date_time::period< ptime, time_duration > time_period; // Time period type. - } -}-
namespace boost { - namespace local_time { - - // Function that creates a tm struct from a local_date_time. - tm to_tm(const local_date_time & lt); - } -}-
namespace boost { - namespace local_time { - class custom_time_zone; - - typedef boost::shared_ptr< dst_calc_rule > dst_calc_rule_ptr; - } -}-
Operators for local_date_time 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 local_time { - local_date_time - operator+(const local_date_time &, const boost::gregorian::months &); - local_date_time - operator+=(local_date_time &, const boost::gregorian::months &); - local_date_time - operator-(const local_date_time &, const boost::gregorian::months &); - local_date_time - operator-=(local_date_time &, const boost::gregorian::months &); - local_date_time - operator+(const local_date_time &, const boost::gregorian::years &); - local_date_time - operator+=(local_date_time &, const boost::gregorian::years &); - local_date_time - operator-(const local_date_time &, const boost::gregorian::years &); - local_date_time - operator-=(local_date_time &, const boost::gregorian::years &); - } -}-
namespace boost { - namespace local_time { - struct partial_date_rule_spec; - struct first_last_rule_spec; - struct last_last_rule_spec; - struct nth_last_rule_spec; - struct nth_kday_rule_spec; - - typedef date_time::dst_day_calc_rule< gregorian::date > dst_calc_rule; // Provides rule of the form starting Apr 30 ending Oct 21. - typedef date_time::day_calc_dst_rule< partial_date_rule_spec > partial_date_dst_rule; // Provides rule of the form first Sunday in April, last Saturday in Oct. - typedef date_time::day_calc_dst_rule< first_last_rule_spec > first_last_dst_rule; // Provides rule of the form first Sunday in April, last Saturday in Oct. - typedef date_time::day_calc_dst_rule< last_last_rule_spec > last_last_dst_rule; // Provides rule of the form last Sunday in April, last Saturday in Oct. - typedef date_time::day_calc_dst_rule< nth_last_rule_spec > nth_last_dst_rule; // Provides rule in form of [1st|2nd|3rd|4th] Sunday in April, last Sunday in Oct. - typedef date_time::day_calc_dst_rule< nth_kday_rule_spec > nth_kday_dst_rule; // Provides rule in form of [1st|2nd|3rd|4th] Sunday in April/October. - typedef date_time::day_calc_dst_rule< nth_kday_rule_spec > nth_day_of_the_week_in_month_dst_rule; // Provides rule in form of [1st|2nd|3rd|4th] Sunday in April/October. - } -}-
namespace boost { - namespace local_time { - struct ambiguous_result; - struct time_label_invalid; - struct dst_not_valid; - - template<typename utc_time_ = posix_time::ptime, - typename tz_type = date_time::time_zone_base<utc_time_> > - class local_date_time_base; - - typedef local_date_time_base local_date_time; // Use the default parameters to define local_date_time. - } -}-
namespace boost { - namespace local_time { - typedef boost::date_time::time_facet< local_date_time, wchar_t > wlocal_time_facet; - typedef boost::date_time::time_facet< local_date_time, char > local_time_facet; - typedef boost::date_time::time_input_facet< local_date_time::utc_time_type, wchar_t > wlocal_time_input_facet; - typedef boost::date_time::time_input_facet< local_date_time::utc_time_type, char > local_time_input_facet; - - // operator<< for local_date_time - see local_time docs for formatting details - template<typename CharT, typename TraitsT> - std::basic_ostream< CharT, TraitsT > & - operator<<(std::basic_ostream< CharT, TraitsT > & os, - const local_date_time & ldt); - - // input operator for local_date_time - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & is, - local_date_time & ldt); - } -}-
namespace boost { - namespace serialization { - BOOST_SERIALIZATION_SPLIT_FREE(boost::date_time::time_zone_base ); - } -}-
namespace boost { - namespace local_time { - typedef boost::date_time::period< local_date_time, boost::posix_time::time_duration > local_time_period; - typedef date_time::time_itr< local_date_time > local_time_iterator; - typedef date_time::second_clock< local_date_time > local_sec_clock; - typedef date_time::microsec_clock< local_date_time > local_microsec_clock; - typedef boost::shared_ptr< time_zone > time_zone_ptr; // Shared Pointer for time_zone and posix_time_zone objects. - } -}-
namespace boost { - namespace local_time { - struct bad_offset; - struct bad_adjustment; - - class posix_time_zone; - - typedef boost::date_time::time_zone_names time_zone_names; - typedef boost::date_time::dst_adjustment_offsets< boost::posix_time::time_duration > dst_adjustment_offsets; - typedef boost::date_time::time_zone_base< boost::posix_time::ptime > time_zone; - } -}-
namespace boost { - namespace local_time { - class time_zone; - - typedef boost::date_time::time_zone_names time_zone_names; - typedef boost::date_time::dst_adjustment_offsets< boost::posix_time::time_duration > dst_adjustment_offsets; - typedef boost::date_time::time_zone_base< boost::posix_time::ptime > time_zone; - typedef boost::shared_ptr< dst_calc_rule > dst_calc_rule_ptr; - typedef boost::date_time::time_zone_base< boost::posix_time::ptime > time_zone_base; - } -}-
namespace boost { - namespace local_time { - typedef date_time::tz_db_base< custom_time_zone, nth_kday_dst_rule > tz_database; // Object populated with boost::shared_ptr<time_zone_base> objects. - } -}-
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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; - } - --
- 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;
-}
-- 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; - }; - --
- Example that gets a month and a year from the user and finds the last day of each remaining month of that year. -
-- /* Simple program that finds the last day of the given month, - * then displays the last day of every month left in the given year. - */ - - #include "boost/date_time/gregorian/gregorian.hpp" - #include <iostream> - - int - main() - { - using namespace boost::gregorian; - - greg_year year(1400); - greg_month month(1); - - // get a month and a year from the user - try { - int y, m; - std::cout << " Enter Year(ex: 2002): "; - std::cin >> y; - year = greg_year(y); - std::cout << " Enter Month(1..12): "; - std::cin >> m; - month = greg_month(m); - } - catch(bad_year by) { - std::cout << "Invalid Year Entered: " << by.what() << '\n' - << "Using minimum values for month and year." << std::endl; - } - catch(bad_month bm) { - std::cout << "Invalid Month Entered" << bm.what() << '\n' - << "Using minimum value for month. " << std::endl; - } - - date start_of_next_year(year+1, Jan, 1); - date d(year, month, 1); - - // add another month to d until we enter the next year. - while (d < start_of_next_year){ - std::cout << to_simple_string(d.end_of_month()) << std::endl; - d += months(1); - } - - return 0; - } - --
- 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> - #include <algorithm> - - /* Define a series of char arrays for short and long name strings - * to be associated with German date output (US names will be - * retrieved from the locale). */ - 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_long_weekday_names[] = - { - "Sonntag", "Montag", "Dienstag", "Mittwoch", - "Donnerstag", "Freitag", "Samstag" - }; - const char* const de_short_weekday_names[] = - { - "Son", "Mon", "Die","Mit", "Don", "Fre", "Sam" - }; - - - int main() - { - using namespace boost::gregorian; - - // create some gregorian objects to output - date d1(2002, Oct, 1); - greg_month m = d1.month(); - greg_weekday wd = d1.day_of_week(); - - // create a facet and a locale for German dates - date_facet* german_facet = new date_facet(); - std::cout.imbue(std::locale(std::locale::classic(), german_facet)); - - // create the German name collections - date_facet::input_collection_type short_months, long_months, - short_weekdays, long_weekdays; - std::copy(&de_short_month_names[0], &de_short_month_names[11], - std::back_inserter(short_months)); - std::copy(&de_long_month_names[0], &de_long_month_names[11], - std::back_inserter(long_months)); - std::copy(&de_short_weekday_names[0], &de_short_weekday_names[6], - std::back_inserter(short_weekdays)); - std::copy(&de_long_weekday_names[0], &de_long_weekday_names[6], - std::back_inserter(long_weekdays)); - - // replace the default names with ours - // NOTE: date_generators and special_values were not replaced as - // they are not used in this example - german_facet->short_month_names(short_months); - german_facet->long_month_names(long_months); - german_facet->short_weekday_names(short_weekdays); - german_facet->long_weekday_names(long_weekdays); - - // output the date in German using short month names - german_facet->format("%d.%m.%Y"); - std::cout << d1 << std::endl; //01.10.2002 - - german_facet->month_format("%B"); - std::cout << m << std::endl; //Oktober - - german_facet->weekday_format("%A"); - std::cout << wd << std::endl; //Dienstag - - - // Output the same gregorian objects using US names - date_facet* us_facet = new date_facet(); - std::cout.imbue(std::locale(std::locale::classic(), us_facet)); - - us_facet->format("%m/%d/%Y"); - std::cout << d1 << std::endl; // 10/01/2002 - - // English names, iso order (year-month-day), '-' separator - us_facet->format("%Y-%b-%d"); - std::cout << d1 << std::endl; // 2002-Oct-01 - - return 0; - - } --
- 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; - - } - --
- 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; - } - --
- 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; - } - --
- 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; - - 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; - } --
- 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; - } --
- 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; - } - --
- 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; - } - --
- 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; - } - --
- Example usage of custom_time_zone as well as posix_time_zone. -
-- /* A simple example for using a custom_time_zone and a posix_time_zone. - */ - - #include "boost/date_time/local_time/local_time.hpp" - #include <iostream> - - int - main() - { - using namespace boost; - using namespace local_time; - using namespace gregorian; - using posix_time::time_duration; - - /***** custom_time_zone *****/ - - // create the dependent objects for a custom_time_zone - time_zone_names tzn("Eastern Standard Time", "EST", - "Eastern Daylight Time", "EDT"); - time_duration utc_offset(-5,0,0); - dst_adjustment_offsets adj_offsets(time_duration(1,0,0), - time_duration(2,0,0), - time_duration(2,0,0)); - // rules for this zone are: - // start on first Sunday of April at 2 am - // end on last Sunday of October at 2 am - // so we use a first_last_dst_rule - first_day_of_the_week_in_month start_rule(Sunday, Apr); - last_day_of_the_week_in_month end_rule(Sunday, Oct); - shared_ptr<dst_calc_rule> nyc_rules(new first_last_dst_rule(start_rule, - end_rule)); - // create more dependent objects for a non-dst custom_time_zone - time_zone_names tzn2("Mountain Standard Time", "MST", - "", ""); // no dst means empty dst strings - time_duration utc_offset2(-7,0,0); - dst_adjustment_offsets adj_offsets2(time_duration(0,0,0), - time_duration(0,0,0), - time_duration(0,0,0)); - // no dst means we need a null pointer to the rules - shared_ptr<dst_calc_rule> phx_rules; - - // create the custom_time_zones - time_zone_ptr nyc_1(new custom_time_zone(tzn, utc_offset, - adj_offsets, nyc_rules)); - time_zone_ptr phx_1(new custom_time_zone(tzn2, utc_offset2, - adj_offsets2, phx_rules)); - - /***** posix_time_zone *****/ - - // create posix_time_zones that are the duplicates of the - // custom_time_zones created above. See posix_time_zone documentation - // for details on full zone names. - std::string nyc_string, phx_string; - nyc_string = "EST-05:00:00EDT+01:00:00,M4.1.0/02:00:00,M10.5.0/02:00:00"; - // nyc_string = "EST-05EDT,M4.1.0,M10.5.0"; // shorter when defaults used - phx_string = "MST-07"; // no-dst - time_zone_ptr nyc_2(new posix_time_zone(nyc_string)); - time_zone_ptr phx_2(new posix_time_zone(phx_string)); - - - /***** show the sets are equal *****/ - - std::cout << "The first zone is in daylight savings from:\n " - << nyc_1->dst_local_start_time(2004) << " through " - << nyc_1->dst_local_end_time(2004) << std::endl; - - std::cout << "The second zone is in daylight savings from:\n " - << nyc_2->dst_local_start_time(2004) << " through " - << nyc_2->dst_local_end_time(2004) << std::endl; - - std::cout << "The third zone (no daylight savings):\n " - << phx_1->std_zone_abbrev() << " and " - << phx_1->base_utc_offset() << std::endl; - - std::cout << "The fourth zone (no daylight savings):\n " - << phx_2->std_zone_abbrev() << " and " - << phx_2->base_utc_offset() << std::endl; - - return 0; - } --
- Example of creating various Daylight Savings Calc Rule objects. -
-- /* A simple example for creating various dst_calc_rule instances - */ - - #include "boost/date_time/gregorian/gregorian.hpp" - #include "boost/date_time/local_time/local_time.hpp" - #include <iostream> - - int - main() - { - using namespace boost; - using namespace local_time; - using namespace gregorian; - - /***** create the necessary date_generator objects *****/ - // starting generators - first_day_of_the_week_in_month fd_start(Sunday, May); - last_day_of_the_week_in_month ld_start(Sunday, May); - nth_day_of_the_week_in_month nkd_start(nth_day_of_the_week_in_month::third, - Sunday, May); - partial_date pd_start(1, May); - // ending generators - first_day_of_the_week_in_month fd_end(Sunday, Oct); - last_day_of_the_week_in_month ld_end(Sunday, Oct); - nth_day_of_the_week_in_month nkd_end(nth_day_of_the_week_in_month::third, - Sunday, Oct); - partial_date pd_end(31, Oct); - - /***** create the various dst_calc_rule objects *****/ - dst_calc_rule_ptr pdr(new partial_date_dst_rule(pd_start, pd_end)); - dst_calc_rule_ptr flr(new first_last_dst_rule(fd_start, ld_end)); - dst_calc_rule_ptr llr(new last_last_dst_rule(ld_start, ld_end)); - dst_calc_rule_ptr nlr(new nth_last_dst_rule(nkd_start, ld_end)); - dst_calc_rule_ptr ndr(new nth_day_of_the_week_in_month_dst_rule(nkd_start, - nkd_end)); - - return 0; - } - --
This example shows a program that calculates the arrival time of a plane that flys from Phoenix to New York. During the flight New York shifts into daylight savings time (Phoenix doesn't because Arizona doesn't use dst).
-#include "boost/date_time/local_time/local_time.hpp"
-#include <iostream>
-
-/* This example shows a program that calculates the arrival time of a plane
- * that flys from Phoenix to New York. During the flight New York shifts
- * into daylight savings time (Phoenix doesn't because Arizona doesn't use
- * dst).
- *
- *
- */
-
-int main()
-{
- using namespace boost::gregorian;
- using namespace boost::local_time;
- using namespace boost::posix_time;
-
-
- //setup some timezones for creating and adjusting local times
- //This user editable file can be found in libs/date_time/data.
- tz_database tz_db;
- tz_db.load_from_file("date_time_zonespec.csv");
- time_zone_ptr nyc_tz = tz_db.time_zone_from_region("America/New_York");
- //Use a
- time_zone_ptr phx_tz(new posix_time_zone("MST-07:00:00"));
-
- //local departure time in phoenix is 11 pm on april 2 2005
- // (ny changes to dst on apr 3 at 2 am)
- local_date_time phx_departure(date(2005, Apr, 2), hours(23),
- phx_tz,
- local_date_time::NOT_DATE_TIME_ON_ERROR);
-
- time_duration flight_length = hours(4) + minutes(30);
- local_date_time phx_arrival = phx_departure + flight_length;
- local_date_time nyc_arrival = phx_arrival.local_time_in(nyc_tz);
-
- std::cout << "departure phx time: " << phx_departure << std::endl;
- std::cout << "arrival phx time: " << phx_arrival << std::endl;
- std::cout << "arrival nyc time: " << nyc_arrival << std::endl;
-
-}
-- Example of calculating seconds elapsed since epoch (1970-Jan-1) using local_date_time. -
-- /* This example demonstrates the use of the time zone database and - * local time to calculate the number of seconds since the UTC - * time_t epoch 1970-01-01 00:00:00. Note that the selected timezone - * could be any timezone supported in the time zone database file which - * can be modified and updated as needed by the user. - * - * To solve this problem the following steps are required: - * 1) Get a timezone from the tz database for the local time - * 2) Construct a local time using the timezone - * 3) Construct a posix_time::ptime for the time_t epoch time - * 4) Convert the local_time to utc and subtract the epoch time - * - */ - - #include "boost/date_time/local_time/local_time.hpp" - #include <iostream> - - int main() - { - using namespace boost::gregorian; - using namespace boost::local_time; - using namespace boost::posix_time; - - tz_database tz_db; - try { - tz_db.load_from_file("../data/date_time_zonespec.csv"); - }catch(data_not_accessible dna) { - std::cerr << "Error with time zone data file: " << dna.what() << std::endl; - exit(EXIT_FAILURE); - }catch(bad_field_count bfc) { - std::cerr << "Error with time zone data file: " << bfc.what() << std::endl; - exit(EXIT_FAILURE); - } - - time_zone_ptr nyc_tz = tz_db.time_zone_from_region("America/New_York"); - date in_date(2004,10,04); - time_duration td(12,14,32); - // construct with local time value - // create not-a-date-time if invalid (eg: in dst transition) - local_date_time nyc_time(in_date, - td, - nyc_tz, - local_date_time::NOT_DATE_TIME_ON_ERROR); - - std::cout << nyc_time << std::endl; - - ptime time_t_epoch(date(1970,1,1)); - std::cout << time_t_epoch << std::endl; - - // first convert nyc_time to utc via the utc_time() - // call and subtract the ptime. - time_duration diff = nyc_time.utc_time() - time_t_epoch; - - //Expected 1096906472 - std::cout << "Seconds diff: " << diff.total_seconds() << std::endl; - - } --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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; - - //date generator functions - date d5 = next_weekday(d4, Sunday); //calculate Sunday following d4 - - //US labor day is first Monday in Sept - nth_day_of_the_week_in_month labor_day(nth_dow::first,Monday, Sep); - //calculate a specific date for 2004 from functor - date d6 = labor_day.get_date(2004); --
- - The following provides some example code using times. - See Time Programming - for more details. - -
-using 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 tomorrow = today + date_duration(1); - ptime tomorrow_start(tomorrow); //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 < tomorrow_start; ++titr) { - std::cout << (*titr) << std::endl; - } --
- The following provides some example code using times. - See Local Time Programming - for more details. - -
-using namespace boost::local_time; - //setup some timezones for creating and adjusting times - //first time zone uses the time zone file for regional timezone definitions - tz_database tz_db; - tz_db.load_from_file("date_time_zonespec.csv"); - time_zone_ptr nyc_tz = tz_db.time_zone_from_region("America/New_York"); - //This timezone uses a posix time zone string definition to create a time zone - time_zone_ptr phx_tz(new posix_time_zone("MST-07:00:00")); - - //local departure time in phoenix is 11 pm on April 2 2005 - // Note that New York changes to daylight savings on Apr 3 at 2 am) - local_date_time phx_departure(date(2005, Apr, 2), hours(23), phx_tz, - local_date_time::NOT_DATE_TIME_ON_ERROR); - - time_duration flight_length = hours(4) + minutes(30); - local_date_time phx_arrival = phx_departure + flight_length; - //convert the phx time to a nyz time - local_date_time nyc_arrival = phx_arrival.local_time_in(nyc_tz); - - //2005-Apr-03 06:30:00 EDT - std::cout << nyc_arrival << std::endl; --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Introduction -- - Usage Examples
-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 9999-Dec-31. 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. -
-Example | -Description | -
---|---|
- | Simple date arithmetic. Retrieve current day from clock. | -
- | Simple parsing and formatting of dates from/to strings | -
- | See if a date is in a set of date periods (eg: is it a holiday/weekend) | -
- | 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. | -
- | Uses date generators to convert abstract specification into concrete set of dates. | -
- 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 from another - date. - Techniques for creating dates include reading the - current date from the clock, - using date iterators, and - date algorithms or generators. -
-- Internally boost::gregorian::date is stored as a 32 bit integer type. The class is specifically - designed to NOT contain virtual functions. This design allows for efficient - calculation and memory usage with large collections of dates. -
-- The construction of a date ensures validates all input such that it is not possible to - construct and 'invalid' date. That is 2001-Feb-29 cannot be constructed as a date. - Various exceptions derived from std::out_of_range are thrown to indicate which aspect - of the date input is invalid. Note that the - special value not-a-date-time can be used as 'invalid' or 'null' date if so desired. -
-#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-
Syntax | -Description | -
---|---|
Example | |
date(greg_year, greg_month, greg_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 |
Syntax | -Description | -
---|---|
Example | |
date from_string(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(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)); |
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()); |
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 | |
greg_day_of_year day_of_year() const |
-Get the day of the year. Number from 1 to 366 | -
date d(2000,Jan,10); -d.day_of_year(); // --> 10 | |
date end_of_month() const |
-Returns a date object set to the last day of the calling objects current month. |
-
date d(2000,Jan,10); -d.day_of_year(); // --> 2000-Jan-31 | |
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 | |
bool is_special() const |
-Returns true if date is any special_value
- |
-
date d(pos_infin); -date d2(not_a_date_time); -date d3(2005,Mar,1); -d.is_special(); // --> true -d2.is_special(); // --> true -d3.is_special(); // --> false | |
special_value as_special() const |
-Returns represented special_value or not_special if the represented date is a normal date. |
-
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. | -
date end_of_month_day() const |
-Returns the last day of the month for the date. | -
date d(2000,Feb,1); -//gets Feb 28 -- 2000 was leap year -date eom = d.end_of_month_day(); |
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" |
Syntax | -Description | -
---|---|
Example | |
operator<< |
-Stream output operator | -
date d(2002,Jan,1); -std::cout << d << std::endl; | |
operator>> |
-Stream input operator. Note: As of version 1.33, streaming operations have been greatly improved. See Date Time IO System for details on exceptions and error conditions. | -
date d(not_a_date_time); -stringstream ss("2002-Jan-01"); -ss >> d; | |
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; |
Functions for converting a date
object to, and from, a tm
struct are provided.
Syntax | -Description | -
---|---|
Example | |
tm to_tm(date) |
-A function for converting a date object to a tm struct. The fields: tm_hour , tm_min , and tm_sec are set to zero. The tm_isdst field is set to -1. |
-
date d(2005,Jan,1); -tm d_tm = to_tm(d); -/* tm_year => 105 - tm_mon => 0 - tm_mday => 1 - tm_wday => 6 (Saturday) - tm_yday => 0 - tm_hour => 0 - tm_min => 0 - tm_sec => 0 - tm_isddst => -1 */ | |
date date_from_tm(tm datetm) |
-A function for converting a tm struct to a date object. The fields: tm_wday , tm_yday , tm_hour , tm_min , tm_sec , and tm_isdst are ignored. |
-
tm d_tm; -d_tm.tm_year = 105; -d_tm.tm_mon = 0; -d_tm.tm_mday = 1; -date d = date_from_tm(d_tm); -// d => 2005-Jan-01 |
- 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. -
-- As of version 1_32 the date_duration class has been typedef'd as days in the boost::gregorian namespace. Throughout the examples you will find days used instead of date_duration. -
-#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-
Syntax | -Description | -
---|---|
Example | |
date_duration(long) |
-Create a duration count. | -
date_duration dd(3); //3 days | |
days(special_values sv) |
-Constructor for infinities, not-a-date-time, max_date_time, and min_date_time | -
days dd1(neg_infin); -days dd2(pos_infin); -days dd3(not_a_date_time); -days dd4(max_date_time); -days dd5(min_date_time); |
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) | |
bool is_special() const |
-Returns true if days is any special_value
- |
-
days dd(pos_infin); -days dd2(not_a_date_time); -days dd3(25); -dd.is_special(); // --> true -dd2.is_special(); // --> true -dd3.is_special(); // --> false |
Syntax | -Description | -
---|---|
Example | |
operator<<, operator>> |
-Streaming operators. Note: As of version 1.33, streaming operations have been greatly improved. See Date Time IO System for more details (including exceptions and error conditions). | -
date d(not_a_date_time); -stringstream ss("2002-Jan-01"); -ss >> d; -std::cout << d; // "2002-Jan-01" - | |
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; |
These additional types are logical representations of spans of days.
-Syntax | -Description | -
---|---|
Example | |
months(int num_of_months) |
-A logical month representation. Depending on the usage, this months object may cover a span of 28 to 31 days. The objects also use a snap to end-of-month behavior when used in conjunction with a date that is the last day of a given month. WARNING: this behavior may lead to unexpected results. See: Reversibility of Operations Pitfall for complete details and alternatives. |
-
months single(1); -date leap_year(2004,Jan,31); -date norm_year(2005,Jan,31); -leap_year + single; // => 2004-Feb-29 -norm_year + single; // => 2005-Feb-28 -date(2005,Jan,1) + single; // => 2005-Feb-01 -date(2005,Feb,1) + single; // => 2005-Mar-01 -date(2005,Feb,28) + single; // => 2005-Mar-31 | |
years(int num_of_years) |
-A logical representation of a year. The years object has the same behavior as the months objects with regards to the end-of-the-month. |
-
years single(1); -date(2003,Feb,28) + single; -// results in => 2004-Feb-29 -date(2004,Feb,29) + single; -// results in => 2005-Feb-28 | |
weeks(int num_of_weeks) |
-A duration type representing a number of n * 7 days. |
-
weeks single(1); -date(2005,Jan,1) + single; // => 2005-Jan-08 |
A natural expectation when adding a number of months to a date, and then subtracting the same number of months, is to end up exactly where you started. This is most often the result the date_time
library provides but there is one significant exception: The snap-to-end-of-month behavior implemented by the months duration type. The months duration type may provide unexpected results when the starting day is the 28th, 29th, or 30th in a 31 day month. The month_iterator is not effected by this issue and is therefore included in the examples to illustrate a possible alternative.
-
When the starting date is in the middle of a month, adding or subtracting any number of months will result in a date that is the same day of month (e.g. if you start on the 15th, you will end on the 15th). When a date is the last day of the month, adding or subtracting any number of months will give a result that is also the last day of the month (e.g if you start on Jan 31st, you will land on: Feb 28th, Mar 31st, etc). -
-- // using months duration type - date d(2005, Nov, 30); // last day of November - d + months(1); // result is last day of December "2005-Dec-31" - d - months(1); // result is last day of October "2005-Oct-31" - - // using month_iterator - month_iterator itr(d); // last day of November - ++itr; // result is last day of December "2005-Dec-31" - --itr; // back to original starting point "2005-Nov-30" - --itr; // last day of October "2005-Oct-31" --
If the start date is the 28th, 29th, or 30th in a 31 day month, the result of adding or subtracting a month may result in the snap-to-end-of-month behavior kicking in unexpectedly. This would cause the final result to be different that the starting date. -
-- // using months duration type - date d(2005, Nov, 29); - d += months(1); // "2005-Dec-29" - d += months(1); // "2006-Jan-29" - d += months(1); // "2006-Feb-28" --> snap-to-end-of-month behavior kicks in - d += months(1); // "2006-Mar-31" --> unexpected result - d -= months(4); // "2005-Nov-30" --> unexpected result, not where we started - - // using month_iterator - month_iterator itr(date(2005, Dec, 30)); - ++itr; // "2006-Jan-30" --> ok - ++itr; // "2006-Feb-28" --> snap-to DOES NOT kick in - ++itr; // "2006-Mar-30" --> ok - --itr; // "2006-Feb-28" --> ok - --itr; // "2006-Jan-30" --> ok - --itr; // "2005-Dec-30" --> ok, back where we started --
The additional duration types (months
, years
, and weeks
) are provided as a convenience and can be easily removed to insure this pitfall never occurs. To remove these types simply undefine BOOST_DATE_TIME_OPTIONAL_GREGORIAN_TYPES.
- 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 date period calculation example provides an example of this. -
-
- A period that is created with beginning and end points being equal, or with a duration of zero, is known as a zero length period. Zero length periods are considered invalid (it is perfectly legal to construct an invalid period). For these periods, the last
point will always be one unit less that the begin
point.
-
- Date periods used in combination with infinity values have the ability to represent complex concepts such as 'until further notice'. -
-#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-
Syntax | -Description | -
---|---|
Example | |
date_period(date, date) |
-Create a period as [begin, end). If end is <= begin then the period will be invalid. | -
date_period dp(date(2002,Jan,10), - date(2002,Jan,12)); | |
date_period(date, days) |
-Create a period as [begin, begin+len) where end point would be begin+len. If len is <= zero then the period will be defined as invalid. | -
date_period dp(date(2002,Jan,10), - days(2)); | |
date_period(date_period) |
-Copy constructor | -
date_period dp1(dp); |
Syntax | -Description | -
---|---|
Example | |
date begin() |
-Return first day of period. | -
date_period dp(date(2002,Jan,1), - date(2002,Jan,10)); -dp.begin() --> 2002-Jan-01 | |
date last() |
-Return last date in the period | -
date_period dp(date(2002,Jan,1), - date(2002,Jan,10)); -dp.last() --> 2002-Jan-09 | |
date end() |
-Return one past the last in period | -
date_period dp(date(2002,Jan,1), - date(2002,Jan,10)); -dp.end() --> 2002-Jan-10 | |
days length() |
-Return the length of the date_period | -
date_period dp(date(2002,Jan,1), - days(2)); -dp.length() --> 2 | |
bool is_null() |
-True if period is not well formed. eg: end less than or equal to begin. | -
date_period dp(date(2002,Jan,10), - date(2002,Jan,1)); -dp.begin() --> true | |
bool contains(date) |
-True if date is within the period. Zero length periods cannot contain any points | -
date d(2002,Jan,1); -date_period dp(d, date(2002,Jan,10)); -dp.contains(date(2002,Jan,2));// true -date_period dp2(d, d); -dp.contains(date(2002,Jan,1));// false | |
bool contains(date_period) |
-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) |
-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) |
-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) |
-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) |
-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) |
-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) |
-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) |
-Combines two periods and any gap between them such that begin = min(p1.begin, p2.begin) 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.span(dp1); // 2002-Jan-01/2002-Jan-31 | |
date_period shift(days) |
-Add duration to both begin and end. | -
date_period dp1(date(2002,Jan,1), - date(2002,Jan,10)); -dp1.shift(days(1)); -// 2002-Jan-02/2002-Jan-11 |
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] |
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>> |
-istream operator for date_period. Uses facet to parse time points. | -
"[2002-Jan-01/2002-Jan-31]" | |
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 |
- Date iterators provide a standard mechanism for iteration through dates. Date iterators are a model of Bidirectional 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. -
-#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-
Syntax | -Description | -
---|---|
Example | |
date_iterator |
-Common (abstract) base class for all day level iterators. | -
day_iterator(date start_date, int day_count=1) |
-Iterate day_count days at a time. This iterator does not provide postfix increment/decrement operators. Only prefix operators are provided. |
-
day_iterator day_itr(date(2005,Jan,1)); -++d_itr; // 2005-Jan-02 -day_iterator 2day_itr(date(2005,Feb,1),2); -++2d_itr; // 2005-Feb-03 | |
week_iterator(...) - Parameters: - date start_date - int week_offset (defaults to 1) |
-Iterate week_offset weeks at a time. This iterator does not provide postfix increment/decrement operators. Only prefix operators are provided. |
-
week_iterator wk_itr(date(2005,Jan,1)); -++wk_itr; // 2005-Jan-08 -week_iterator 2wk_itr(date(2005,Jan,1),2); -++2wk_itr; // 2005-Feb-15 | |
month_iterator(...) - Parameters: - date start_date - int month_offset (defaults to 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 (e.g. Jan 31 + 1 month) adjust back to end of month (for more details and examples of this, see Reversibility of Operations Pitfall. NOTE: the month_iterator is not effected by this pitfall.) This iterator does not provide postfix increment/decrement operators. Only prefix operators are provided. |
-
month_iterator m_itr(date(2005,Jan,1)); -++m_itr; // 2005-Feb-01 -month_iterator 2m_itr(date(2005,Feb,1),2); -++2m_itr; // 2005-Apr-01 | |
year_iterator(...) - Parameters: - date start_date - int year_offset (defaults to 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). This iterator does not provide postfix increment/decrement operators. Only prefix operators are provided. | -
year_iterator y_itr(date(2005,Jan,1)); -++y_itr; // 2006-Jan-01 -year_iterator 2y_itr(date(2005,Feb,1),2); -++2y_itr; // 2007-Feb-01 |
- 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. -
-#include "boost/date_time/gregorian/gregorian.hpp"-
Class and get_date Parameter | -Description | -
---|---|
Example | |
year_based_generator -date get_date(greg_year year) |
-A unifying (abstract) 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, - greg_month) -date get_date(greg_year 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, - greg_month) -date get_date(greg_year 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 | |
nth_day_of_the_week_in_month(week_num, - greg_weekday, - greg_month) -date get_date(greg_year year) |
-
-week_num is a public enum member of nth_day_of_the_week_in_month . Calculate something like first Monday of January, second Tuesday of March, Third Sunday of December, etc. (first through fifth are provided, fifth is the equivalent of last) |
-
typedef nth_day_of_the_week_in_month nth_dow; -nth_dow ndm(nth_dow::third, Monday,Jan); -date d = ndm.get_date(2002); -//2002-Jan-21 | |
partial_date(greg_day, greg_month) -date get_date(greg_year 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) -date get_date(date d) |
-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) -date get_date(date d) |
-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 Prototype | -Description | -
---|---|
Example | |
days days_until_weekday date, 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(date, 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(date, 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(date, 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 |
- 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. -
-#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-
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 |
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Introduction -- - Usage Examples
-- The library supports 4 main extensions for the management of local times. This includes -
-local_date_time -- locally adjusted time point |
posix_time_zone -- time zone defined by posix string (eg: "EST10EDT,M10.5.0,M3.5.0/03") |
time_zone_database -- get time zones by region from .csv file (eg: America/New York) |
time_zone -- abstract time zone interface |
- Together, these extensions define a time system adjusted for recording times related to a specific earth location. This time system utilizes all the features and benefits of the posix_time system (see posix_time for full details). It uses a time_zone object which contains all the necessary data/rules to enable adjustments to and from various time zones. The time_zone objects used in date_time are handled via a boost::shared_ptr<boost::local_time::time_zone>. -
-- The phrase "wall-clock" refers to the time that would be shown on a wall clock in a particular time zone at any point in time. Local_time uses a time zone object to account for differences in time zones and daylight savings adjustments. For example: While 5:00 pm, October 10, 2004 in Sydney Australia occurs at exactly the same instant as 3:00 am, October 10, 2004 in New York USA, it is a 14 hour difference in wall-clock times. However, a point in time just one day later will result in a 16 hour difference in wall-clock time due to daylight savings adjustments in both time zones. The local_time system tracks these by means of a time point, stored as UTC, and time_zone objects that contain all the necessary data to correctly calculate wall-clock times. -
-Example | -Description | -
---|---|
Simple Time Zone | -Side by side examples of Time Zone usage. Both custom_time_zone and posix_time_zone are shown. | -
Daylight Savings Calc Rules | -Simple example showing the creation of all five dst_calc_rule types. | -
Seconds Since Epoch | -Example that calculates the total seconds elapsed since the epoch (1970-Jan-01) utilizing local_date_time. | -
- The time_zone_base class is an abstract base class template for representing time zones. Time zones are a set of data and rules that provide information about a time zone. The date_time library handles time_zones by means of a boost::shared_ptr<time_zone_base>. A user's custom time zone class will work in the date_time library by means of this shared_ptr. -
-- For convienience, the time_zone_base class is typedef'd as time_zone. All references in the documentation to time_zone, are referring to this typedef. -
-- The time_zone_base class is defined in the header: -
-#include "boost/date_time/time_zone_base.hpp" --
- A default constructor is provided in the time_zone_base class. There are no private data members in this base class to initialize. -
-- Template parameters are time_type (typically posix_time::ptime) and CharT (defaults to char). -
-- All of the accessors listed here are pure virtual functions. -
-Syntax | -Description | -
---|---|
-string_type dst_zone_abbrev(); |
-Returns the daylight savings abbreviation for the represented time zone. | -
-string_type std_zone_abbrev(); |
-Returns the standard abbreviation for the represented time zone. | -
-string_type dst_zone_name(); |
-Returns the daylight savings name for the represented time zone. | -
-string_type std_zone_name(); |
-Returns the standard name for the represented time zone. | -
bool has_dst(); |
-Returns true if this time zone does not make a daylight savings shift. | -
-time_type dst_local_start_time(year_type); |
-The date and time daylight savings time begins in given year. | -
-time_type dst_local_end_time(year_type); |
-The date and time daylight savings time ends in given year. | -
-time_duration_type base_utc_offset(); |
-The amount of time offset from UTC (typically in hours). | -
-time_duration_type dst_offset(); |
-The amount of time shifted during daylight savings. | -
-std::string to_posix_string(); |
-Returns a posix time zone string representation of this time_zone_base object. For a detailed description of a posix time zone string see posix_time_zone. | -
- A posix_time_zone object is a set of data and rules that provide information about a time zone. Information such as the offset from UTC, it's name and abbreviation, as well as daylight savings rules, called dst_calc_rules. These rules are stored as a boost::shared_ptr<dst_calc_rules>. -
-- As a convenience, a typedef for shared_ptr<dst_calc_rules> is provided. -
-typedef boost::shared_ptr<dst_calc_rules> local_time::dst_calc_rule_ptr;-
- A posix_time_zone is unique in that the object is created from a Posix time zone string (IEEE Std 1003.1). A POSIX time zone string takes the form of: -
-
- "std offset dst [offset],start[/time],end[/time]" (w/no spaces).
'std' specifies the abbrev of the time zone. 'offset' is the offset from UTC. 'dst' specifies the abbrev of the time zone during daylight savings time. The second offset is how many hours changed during DST. 'start' and 'end' are the dates when DST goes into (and out of) effect. 'offset' takes the form of: -
-
- [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}
'time' and 'offset' take the same form. 'start' and 'end' can be one of three forms: -
-
- Mm.w.d {month=1-12, week=1-5 (5 is always last), day=0-6}
- Jn {n=1-365 Feb29 is never counted}
- n {n=0-365 Feb29 is counted in leap years}
- Exceptions will be thrown under the following conditions: -
-As stated above, the 'offset' and '/time' portions of the string are not required. If they are not given they default to 01:00 for 'offset', and 02:00 for both occurrences of '/time'. -
-- Some examples are: -
-
- "PST-8PDT01:00:00,M4.1.0/02:00:00,M10.1.0/02:00:00"
- "PST-8PDT,M4.1.0,M10.1.0"
These two are actually the same specification (defaults were used in the second string). This zone lies eight hours west of GMT and makes a one hour shift forward during daylight savings time. Daylight savings for this zone starts on the first Sunday of April at 2am, and ends on the first Sunday of October at 2am. -
-
- "MST-7"
This zone is as simple as it gets. This zone lies seven hours west of GMT and has no daylight savings. -
-
- "EST10EDT,M10.5.0,M3.5.0/03"
This string describes the time zone for Sydney Australia. It lies ten hours east of GMT and makes a one hour shift forward during daylight savings. Being located in the southern hemisphere, daylight savings begins on the last Sunday in October at 2am and ends on the last Sunday in March at 3am. -
-
- "FST+3FDT02:00,J60/00,J304/02"
This specification describes a fictitious zone that lies three hours east of GMT. It makes a two hour shift forward for daylight savings which begins on March 1st at midnight, and ends on October 31st at 2am. The 'J' designation in the start/end specs signifies that counting starts at one and February 29th is never counted. -
-
- "FST+3FDT,59,304"
This specification is significant because of the '59'. The lack of 'J' for the start and end dates, indicates that the Julian day-count begins at zero and ends at 365. If you do the math, you'll see that allows for a total of 366 days. This is fine in leap years, but in non-leap years '59' (Feb-29) does not exist. This will construct a valid posix_time_zone object but an exception will be thrown if the date of '59' is accessed in a non-leap year. Ex: -
-posix_time_zone leap_day(std::string("FST+3FDT,59,304")); -leap_day.dst_local_start_time(2004); // ok -leap_day.dst_local_start_time(2003); // Exception thrown-
- The posix_time_zone objects are used via a boost::shared_ptr<local_time::time_zone_base>. As a convenience, a typedef for boost::shared_ptr<local_time::time_zone_base> is provided: -
-typedef boost::shared_ptr<time_zone_base> local_time::time_zone_ptr;-
- See Simple time zone for a side by side example of time_zone and posix_time_zone usage. -
-- The inclusion of a single header will bring in all boost::local_time types, functions, and IO operators. -
-#include "boost/date_time/local_time/local_time.hpp"-
Syntax | -Example | -
---|---|
posix_time_zone(std::string) |
-std::string nyc("EST-5EDT,M4.1.0,M10.5.0"); -time_zone_ptr zone(new posix_time_zone(nyc)); |
-
Syntax | -Description | -
---|---|
Example | |
std::string dst_zone_abbrev() |
-Returns the daylight savings abbreviation for the represented time zone. | -
nyc_zone_sh_ptr->dst_zone_abbrev(); // "EDT" | |
std::string std_zone_abbrev() |
-Returns the standard abbreviation for the represented time zone. | -
nyc_zone_sh_ptr->std_zone_abbrev(); // "EST" | |
std::string dst_zone_name() |
-Returns the daylight savings ABBREVIATION for the represented time zone. | -
nyc_zone_sh_ptr->dst_zone_name(); // "EDT" | |
std::string std_zone_name() |
-Returns the standard ABBREVIATION for the represented time zone. | -
nyc_zone_sh_ptr->std_zone_name(); // "EST" | |
bool has_dst() |
-Returns true when time_zone's shared_ptr to dst_calc_rules is not NULL. | -
nyc_zone_sh_ptr->has_dst(); // true -phx_zone_sh_ptr->has_dst(); // false | |
-ptime dst_local_start_time(greg_year) |
-The date and time daylight savings time begins in given year. Returns not_a_date_time if this zone has no daylight savings. | -
nyc_zone_sh_ptr->dst_local_start_time(2004); -// 2004-Apr-04 02:00 | |
-ptime dst_local_end_time(greg_year) |
-The date and time daylight savings time ends in given year. Returns not_a_date_time if this zone has no daylight savings. | -
nyc_zone_sh_ptr->dst_local_end_time(2004); -// 2004-Oct-31 02:00 | |
-time_duration base_utc_offset() |
-The amount of time offset from UTC (typically in hours). | -
nyc_zone_sh_ptr->base_utc_offset(); // -05:00 | |
posix_time::time_duration dst_offset() |
-The amount of time shifted during daylight savings. | -
nyc_zone_sh_ptr->dst_offset(); // 01:00 | |
std::string to_posix_string() |
-Returns a posix time zone string representation of this time_zone_base object. Depending on how the time_zone object was created, the date-spec format of the string will be in either 'M' notation or 'n' notation. Every possible date-spec that can be represented in 'J' notation can also be represented in 'n' notation. The reverse is not true so only 'n' notation is used for these types of date-specs. For a detailed description of a posix time zone string see posix_time_zone. | -
nyc_zone_sh_ptr->to_posix_string(); -// "EST-05EDT+01,M4.1.0/02:00,M10.5.0/02:00" -phx_zone_sh_ptr->to_posix_string(); -// "MST-07" - |
- The local_time system depends on the ability to store time zone information. Our Time Zone Database (tz_database) is a means of permanently storing that data. The specifications for many time zones (377 at this time) are provided. These specifications are based on data found in the zoneinfo datebase. The specifications are stored in the file:
-libs/date_time/data/date_time_zonespec.csv-
. While this file already contains specifications for many time zones, it's real intent is for the user to modify it by adding (or removing) time zones to fit their application. See Data File Details to learn how this is accomplished. -
-- The inclusion of a single header will bring in all boost::local_time types, functions, and IO operators. -
-#include "boost/date_time/local_time/local_time.hpp" --
- The only constructor takes no arguments and creates an empty database. It is up to the user to populate the database. This is typically achieved by loading the desired datafile, but can also be accomplished by means of the add_record(...)
function (see the Accessors table). A local_time::data_not_accessible
exception will be thrown if given zonespec file cannot be found. local_time::bad_field_count
exception will be thrown if the number of fields in given zonespec file is incorrect.
-
Syntax | -Description | -
---|---|
tz_database() |
-Constructor creates an empty database. | -
tz_database tz_db; | |
bool load_from_file(std::string) |
-Parameter is path to a time zone spec csv file (see Data File Details for details on the contents of this file). This function populates the database with time zone records found in the zone spec file. A local_time::data_not_accessible exception will be thrown if given zonespec file cannot be found. local_time::bad_field_count exception will be thrown if the number of fields in given zonespec file is incorrect. |
-
tz_database tz_db; -tz_db.load_from_file("./date_time_zonespec.csv"); |
Syntax | -Description | -
---|---|
Example | |
bool tz_db.add_record(std::string id, - time_zone_ptr tz); |
-Adds a time_zone, or a posix_time_zone, to the database. ID is the region name for this zone (Ex: "America/Phoenix"). | -
time_zone_ptr zone( - new posix_time_zone("PST-8PDT,M4.1.0,M10.1.0") -); -std::string id("America/West_Coast"); -tz_db.add_record(id, zone); | |
time_zone_ptr - tz_db.time_zone_from_region(string id); |
-Returns a time_zone, via a time_zone_ptr, that matches the region listed in the data file. A null pointer is returned if no match is found. - | -
time_zone_ptr nyc = - tz_db.time_zone_from_region("America/New_York"); | |
vector<string> tz_db.region_list(); |
-Returns a vector of strings that holds all the region ID strings from the database. | -
std::vector<std::string> regions; -regions = tz_db.region_list(); |
- The csv file containing the zone_specs used by the boost::local_time::tz_database is intended to be customized by the library user. When customizing this file (or creating your own) the file must follow a specific format. -
-- This first line is expected to contain column headings and is therefore -not processed by the tz_database. -
-- Each record (line) must have eleven fields. Some of those fields can be empty. Every field (even empty ones) must be enclosed in double-quotes. -
-
- Ex:
- "America/Phoenix" <- string enclosed in quotes
- "" <- empty field
-
- Some fields represent a length of time. The format of these fields must be: -
-
- "{+|-}hh:mm[:ss]" <- length-of-time format
-
- Where the plus or minus is mandatory and the seconds are optional. -
-- Since some time zones do not use daylight savings it is not always necessary for every field in a zone_spec to contain a value. All zone_specs must have at least ID and GMT offset. Zones that use daylight savings must have all fields filled except: STD ABBR, STD NAME, DST NAME. You should take note that DST ABBR is mandatory for zones that use daylight savings (see field descriptions for further details). -
-- Contains the identifying string for the zone_spec. Any string will do as long as it's unique. No two ID's can be the same. -
-- These four are all the names and abbreviations used by the time zone being described. While any string will do in these fields, care should be taken. These fields hold the strings that will be used in the output of many of the local_time classes. -
-- This is the number of hours added to utc to get the local time before any daylight savings adjustments are made. Some examples are: America/New_York offset -5 hours, and Africa/Cairo offset +2 hours. The format must follow the length-of-time format described above. -
-- The amount of time added to gmt_offset when daylight savings is in effect. The format must follow the length-of-time format described above. -
-- NOTE: more rule capabilities are needed - this portion of the tz_database is incomplete -
-- This is a specially formatted string that describes the day of year in which the transition take place. It holds three fields of it's own, separated by semicolons. -
-- Examples are: "-1;5;9"="Last Friday of September", "2;1;3"="Second Monday of March" -
-- Start time is the number of hours past midnight, on the day of the start transition, the transition takes place. More simply put, the time of day the transition is made (in 24 hours format). The format must follow the length-of-time format described above with the exception that it must always be positive. -
-- See DST Start date rule. The difference here is this is the day daylight savings ends (transition to STD). -
-- Same as Start time. -
-- A custom_time_zone object is a set of data and rules that provide information about a time zone. Information such as the offset from UTC, it's name and abbreviation, as well as daylight savings rules, called dst_calc_rules. These rules are handled via a boost::shared_ptr<dst_calc_rules>. Not all time zones utilize daylight savings, therefore, time_zone objects can be used with a NULL-assigned shared_ptr. -
-- As a convenience, a typedef for shared_ptr<dst_calc_rules> is provided. -
-typedef boost::shared_ptr<dst_calc_rules> local_time::dst_calc_rule_ptr;-
- The time_zone objects are used via a boost::shared_ptr<local_time::time_zone>. As a convenience, a typedef for boost::shared_ptr<local_time::time_zone> is provided: -
-typedef boost::shared_ptr<time_zone> local_time::time_zone_ptr;-
- The inclusion of a single header will bring in all boost::local_time types, functions, and IO operators. -
-#include "boost/date_time/local_time/local_time.hpp"-
- Construction of a custom_time_zone is dependent on four objects: a - time_duration, a time_zone_names, a dst_adjustment_offsets, and a shared_ptr to a dst_calc_rule. -
-Syntax | -Example | -
---|---|
custom_time_zone(...) - Parameters: - names, - gmt_offset, - dst_offsets, - dst_rules |
-See simple_time_zone example for time_zone usage | -
Syntax | -Description | -
---|---|
Example | |
std::string dst_zone_abbrev() |
-Returns the daylight savings abbreviation for the represented time zone. | -
nyc_zone_sh_ptr->dst_zone_abbrev(); -// "EDT" | |
std::string std_zone_abbrev() |
-Returns the standard abbreviation for the represented time zone. | -
nyc_zone_sh_ptr->std_zone_abbrev(); -// "EST" | |
std::string dst_zone_name() |
-Returns the daylight savings name for the represented time zone. | -
nyc_zone_sh_ptr->dst_zone_name(); -// "Eastern Daylight Time" | |
std::string std_zone_name() |
-Returns the standard name for the represented time zone. | -
nyc_zone_sh_ptr->std_zone_name(); -// "Eastern Standard Time" | |
bool has_dst() |
-Returns true when custom_time_zone's shared_ptr to dst_calc_rules is not NULL. | -
nyc_zone_sh_ptr->has_dst(); -// true -phx_zone_sh_ptr->has_dst(); -// false | |
dst_local_start_time(...) - Return Type: - ptime - Parameter: - greg_year |
-The date and time daylight savings time begins in given year. Returns not_a_date_time if this zone has no daylight savings. | -
nyc_ptr->dst_local_start_time(2004); -// 2004-Apr-04 02:00 | |
dst_local_end_time(...) - Return Type: - ptime - Parameter: - greg_year |
-The date and time daylight savings time ends in given year. Returns not_a_date_time if this zone has no daylight savings. | -
nyc_ptr->dst_local_end_time(2004); -// 2004-Oct-31 02:00 | |
time_duration base_utc_offset() |
-The amount of time offset from UTC (typically in hours). | -
nyc_ptr->base_utc_offset(); -// -05:00 | |
time_duration dst_offset() |
-The amount of time shifted during daylight savings. | -
nyc_zone_sh_ptr->dst_offset(); -// 01:00 | |
std::string to_posix_string() |
-Returns a posix time zone string representation of this time_zone object. Depending on how the time_zone object was created, the date-spec format of the string will be in either 'M' notation or 'n' notation. Every possible date-spec that can be represented in 'J' notation can also be represented in 'n' notation. The reverse is not true so only 'n' notation is used for these types of date-specs. For a detailed description of a posix time zone string see posix_time_zone. | -
nyc_ptr->to_posix_string(); -// "EST-05EDT+01,M4.1.0/02:00,M10.5.0/02:00" -phx_ptr->to_posix_string(); -// "MST-07" - |
- The time_zone_names_base type is an immutable template class of four strings. One each for the name and abbreviation in standard time and daylight savings time. The time_zone_names type is a typedef of time_zone_names_base<char>. -
-Syntax | -Description | -
---|---|
Example | |
time_zone_names(...) - Parameters: - string std_name - string std_abbrev - string dst_name - string dst_abbrev |
-The only constructor, all four strings must be provided. | -
string sn("Eastern Standard Time"); -string sa("EST"); -string dn("Eastern Daylight Time"); -string da("EDT"); -time_zone_names nyc_names(sn, sa, - dn, da); | |
std::string std_zone_name() |
-Returns the standard zone name | -
nyc_names.std_zone_name(); -// "Eastern Standard Time" | |
std::string std_zone_abbrev() |
-Returns the standard zone abbreviation | -
nyc_names.std_zone_abbrev(); -// "EST" | |
std::string dst_zone_name() |
-Returns the daylight savings zone name | -
nyc_names.std_zone_name(); -// "Eastern Daylight Time" | |
std::string dst_zone_abbrev() |
-Returns the daylight savings zone abbreviation | -
nyc_names.std_zone_abbrev(); -// "EDT" |
- The dst_adjustment_offsets type is a collection of three time_duration objects. -
-Syntax | -Description | -
---|---|
Example | |
dst_adjustment_offsets(...) - Parameters: - time_duration dst_adjust - time_duration start_offset - time_duration end_offset |
-The first time_duration is the daylight savings adjustment. The second is the time which daylight savings starts on the start day. The third is the time daylight savings ends on the ending day. | -
-dst_adjustment_offsets(hours(1), - hours(2), - hours(2)); |
- Daylight savings calc rules, named dst_calc_rules, are a series of objects that group appropriate date_generators together to form rule sets. The individual rules objects are used via dst_calc_rule_ptr. -
-- For a complete example of all five dst_calc_rule types, see: calc_rules example. -
-Syntax | -Description | -
---|---|
partial_date_dst_rule(...) - Parameters: - start_rule - end_rule |
-Both the start and end rules are of type gregorian::partial_date. | -
first_last_dst_rule(...) - Parameters: - start_rule - end_rule |
-The DST start rule is of type gregorian::first_day_of_the_week_in_month and the end rule is of type gregorian::last_day_of_the_week_in_month. | -
last_last_dst_rule(...) - Parameters: - start_rule - end_rule |
-Both the start and end rules are of type gregorian::last_day_of_the_week_in_month. | -
nth_last_dst_rule(...) - Parameters: - start_rule - end_rule |
-The DST start rule is of type gregorian::nth_day_of_the_week_in_month and the end rule is of type gregorian::last_day_of_the_week_in_month. | -
nth_kday_dst_rule(...) - Parameters: - start_rule - end_rule) -(see note* below) |
-Both rules are of type gregorian::nth_day_of_the_week_in_month. | -
- * Note: The name "nth_kday_dst_rule" is a bit cryptic. Therefore, a more descriptive name, "nth_day_of_the_week_in_month_dst_rule", is also provided. -
-- A local_date_time object is a point in time and an associated time zone. The time is represented internally as UTC. -
-- The inclusion of a single header will bring in all boost::local_time types, -functions, and IO operators. -
-- #include "boost/date_time/local_time/local_time.hpp" --
- Creation of a local_date_time object from clock is possible with either second, or sub second resolution. -
-Syntax | -Example | -
---|---|
local_microsec_clock(...) - Return Type: - local_date_time - Parameter: - time_zone_ptr |
-time_zone_ptr zone( - new posix_time_zone("MST-07") -); -local_date_time ldt = - local_microsec_clock::local_time( - zone); |
-
local_sec_clock(...) - Return Type: - local_date_time - Parameter: - time_zone_ptr |
-time_zone_ptr zone( - new posix_time_zone("MST-07") -); -local_date_time ldt = - local_sec_clock::local_time(zone); |
-
- Construction of a local_date_time object can be done with a ptime and a time_zone_ptr where the ptime represents UTC time. Construction with a wall-clock representation takes the form of a date, a time_duration, a time_zone_ptr, and a fourth parameter that addresses the following complication. -
-- Construction from a wall-clock rep may result in differing shifts for a particular time zone, depending on daylight savings rules for that zone. This means it is also possible to create a local_date_time with a non-existent, or duplicated, UTC representation. These cases occur during the forward shift in time that is the transition into daylight savings and during the backward shift that is the transition out of daylight savings. The user has two options for handling these cases: a bool flag that states if the time is daylight savings, or an enum that states what to do when either of these cases are encountered. -
-
- The bool flag is ignored when the given time_zone has no daylight savings specification. When the daylight savings status of a given time label is calculated and it does not match the flag, a local_time::dst_not_valid
exception is thrown. If a time label is invalid (does not exist), a local_time::time_label_invalid
exception is thrown.
-
- There are two elements in the local_date_time::DST_CALC_OPTIONS
enum: EXCEPTION_ON_ERROR
and NOT_DATE_TIME_ON_ERROR
. The possible exceptions thrown are a local_time::ambiguous_result
or a local_time::time_label_invalid
. The NOT_DATE_TIME_ON_ERROR
sets the time value to the special value local_time::not_a_date_time
in the event of either a invalid or an ambiguous time label.
-
Syntax | -Description | -
---|---|
Example | |
local_date_time(...) - Parameters: - posix_time::ptime - time_zone_ptr |
-The given time is expected to be UTC. Therefore, the given time will be adjusted according to the offset described in the time zone. | -
-// 3am, 2004-Nov-05 local time -ptime pt(date(2004,Nov,5), - hours(10)); -time_zone_ptr zone( - new posix_time_zone("MST-07")); -local_date_time az(pt, zone); | |
local_date_time(...) - Parameters: - date - time_duration - time_zone_ptr - bool |
-The passed time information understood to be in the passed tz. The DST flag must be passed to indicate whether the time is in daylight savings or not. May throw a dst_not_valid or time_label_invalid exception. |
-
date d(2004,Nov,5); -time_duration td(5,0,0,0); -string z("PST-8PDT,M4.1.0,M10.1.0") -time_zone_ptr zone( - new posix_time_zone(z)); -local_date_time nyc(d, td, - zone, false); | |
local_date_time(...) - Parameters: - date - time_duration - time_zone_ptr - DST_CALC_OPTIONS |
-The passed time information understood to be in the passed tz. The DST flag is calculated according to the specified rule. May throw a ambiguous_result or time_label_invalid exception. |
-
date d(2004,Nov,5); -time_duration td(5,0,0,0); -string z("PST-8PDT,M4.1.0,M10.1.0") -time_zone_ptr zone( - new posix_time_zone(z)); -local_date_time nyc(d, td, zone, - NOT_DATE_TIME_ON_ERROR); | |
local_date_time(local_date_time); |
-Copy Constructor. | -
local_date_time az_2(az); | |
local_date_time(...) - Parameters: - special_values - time_zone_ptr |
-Special Values constructor. | -
time_zone_ptr zone( - new posix_time_zone("MST-07") -); -local_date_time nadt(not_a_date_time, - zone); -// default NULL time_zone_ptr -local_date_time nadt(pos_infin); |
Syntax | -Description | -
---|---|
Example | |
time_zone_ptr zone() |
-Returns associated time_zone object via a time_zone_ptr | -
bool is_dst() |
-Determines if time value is in DST for associated zone. | -
ptime utc_time() |
-Converts the local time value to a UTC value. | -
ptime pt(date(2004,Nov,5), - hours(10)); -time_zone_ptr zone( - new posix_time_zone("MST-07")); -local_date_time az(pt, zone); -az.utc_time(); // 10am 2004-Nov-5 | |
ptime local_time() |
-Returns the local time for this object (Wall-clock). | -
ptime pt(date(2004,Nov,5), - hours(10)); -time_zone_ptr zone( - new posix_time_zone("MST-07")); -local_date_time az(pt, zone); -az.utc_time(); // 10am 2004-Nov-5 -az.local_time(); // 3am 2004-Nov-5 | |
local_time_in(...) - Return Type: - local_date_time - Parameters: - time_zone_ptr - time_duration |
-Returns a local_date_time representing the same UTC time as calling object, plus optional time_duration, with given time zone. | -
local_date_time nyc = az.local_time_in(nyc_zone); -// nyc == 7am 2004-Nov-5 | |
bool is_infinity() const |
-Returns true if local_date_time is either positive or negative infinity | -
local_date_time ldt(pos_infin); -ldt.is_infinity(); // --> true | |
bool is_neg_infinity() const |
-Returns true if local_date_time is negative infinity | -
local_date_time ldt(neg_infin); -ldt.is_neg_infinity(); // --> true | |
bool is_pos_infinity() const |
-Returns true if local_date_time is positive infinity | -
local_date_time ldt(neg_infin); -ldt.is_pos_infinity(); // --> true | |
bool is_not_a_date_time() const |
-Returns true if value is not a date | -
local_date_time ldt(not_a_date_time); -ldt.is_not_a_date_time(); // --> true | |
bool is_special() const |
-Returns true if local_date_time is any special_value
- |
-
local_date_time ldt(pos_infin); -local_date_time ldt2(not_a_date_time); -time_zone_ptr - mst(new posix_time_zone("MST-07")); -local_date_time - ldt3(local_sec_clock::local_time(mst)); -ldt.is_special(); // --> true -ldt2.is_special(); // --> true -ldt3.is_special(); // --> false |
Syntax | -Description | -
---|---|
Example | |
operator<< |
-Output streaming operator. This operator is part of the v1.33 IO addition to date_time. For complete details on this feature see Date Time IO. The default output is shown in this example. | -
-time_zone_ptr zone(new posix_time_zone("MST-07"); -local_date_time ldt(date(2005,Jul,4), - hours(20), - false); -std::cout << ldt << std::endl; -// "2005-Jul-04 20:00:00 MST" - | |
operator>> |
-Input streaming operator. This operator is part of the v1.33 IO addition to date_time. For complete details on this feature see Date Time IO. At this time, local_date_time objects can only be streamed in with a Posix Time Zone string. A complete description of a Posix Time Zone string can be found in the documentation for the posix_time_zone class. |
-
stringstream ss; -ss.str("2005-Jul-04 20:00:00 MST-07"); -ss >> ldt; - | |
operator==, operator!=, -operator>, operator<, -operator>=, operator<= |
-A full complement of comparison operators | -
ldt1 == ldt2, etc | |
operator+, operator+=, -operator-, operator-= |
-Addition, subtraction, and shortcut operators for local_date_time and date duration types. These include: days , months , and years . |
-
ldt + days(5), etc | |
operator+, operator+=, -operator-, operator-= |
-Addition, subtraction, and shortcut operators for local_date_time and time_duration . |
-
ldt + hours(5), etc |
Function for converting a local_date_time
object to a tm
struct is provided.
Syntax | -Description | -
---|---|
Example | |
tm to_tm(local_date_time) |
-A function for converting a local_date_time object to a tm struct. |
-
-// 6am, 2005-Jul-05 local time -std::string z("EST-05EDT,M4.1.0,M10.1.0"); -ptime pt(date(2005,Jul,5), - hours(10)); -time_zone_ptr zone( new posix_time_zone(z)); -local_date_time ldt(pt, zone); -tm ldt_tm = to_tm(ldt); -/* tm_year => 105 - tm_mon => 6 - tm_mday => 5 - tm_wday => 2 (Tuesday) - tm_yday => 185 - tm_hour => 6 - tm_min => 0 - tm_sec => 0 - tm_isddst => 1 */ |
- The class boost::local_time::local_time_period
provides direct representation for ranges between two local times. Periods provide the ability to simplify some types of calculations by simplifying the conditional logic of the program.
-
- A period that is created with beginning and end points being equal, or with a duration of zero, is known as a zero length period. Zero length periods are considered invalid (it is perfectly legal to construct an invalid period). For these periods, the last
point will always be one unit less that the begin
point.
-
#include "boost/date_time/local_time/local_time.hpp" //include all types plus i/o -or -#include "boost/date_time/local_time/local_time_types.hpp" //no i/o just types-
Syntax | -Description | -
---|---|
Example | |
local_time_period(...) - Parameters: - local_date_time beginning - local_date_time end |
-Create a period as [begin, end). If end is <= begin then the period will be defined as invalid. | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - beg(ptime(date(2005,Jan,1),hours(0)), zone); -local_date_time - end(ptime(date(2005,Feb,1),hours(0)), zone); -// period for the entire month of Jan 2005 -local_time_period ltp(beg, end); | |
local_time_period(...) - Parameters: - local_date_time beginning - time_duration length |
-Create a period as [begin, begin+len) where end would be begin+len. If len is <= zero then the period will be defined as invalid. | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - beg(ptime(date(2005,Jan,1),hours(0)), zone); -// period for the whole day of 2005-Jan-01 -local_time_period ltp(beg, hours(24)); | |
local_time_period(local_time_period rhs) |
-Copy constructor | -
local_time_period ltp1(ltp); |
Syntax | -Description | -
---|---|
Example | |
local_date_time begin() |
-Return first local_date_time of the period. | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - ldt((ptime(date(2005,Jan,1)),hours(0)), zone); -local_time_period ltp(ldt, hours(2)); -ltp.begin(); // => 2005-Jan-01 00:00:00 | |
local_date_time last() |
-Return last local_date_time in the period | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - ldt((ptime(date(2005,Jan,1),hours(0))), zone); -local_time_period ltp(ldt, hours(2)); -ltp.last(); // => 2005-Jan-01 01:59:59.999999999 | |
local_date_time end() |
-Return one past the last in period | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - ldt((ptime(date(2005,Jan,1),hours(0))), zone); -local_time_period ltp(ldt, hours(2)); -ltp.end(); // => 2005-Jan-01 02:00:00 | |
time_duration length() |
-Return the length of the local_time period. | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - ldt((ptime(date(2005,Jan,1),hours(0))), zone); -local_time_period ltp(ldt, hours(2)); -ltp.length(); // => 02:00:00 | |
bool is_null() |
-True if period is not well formed. eg: end less than or equal to begin. | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - beg((ptime(date(2005,Feb,1),hours(0))), zone); -local_date_time - end((ptime(date(2005,Jan,1),hours(0))), zone); -local_time_period ltp(beg, end); -ltp.is_null(); // => true | |
bool contains(local_date_time) |
-True if local_date_time is within the period. Zero length periods cannot contain any points | -
time_zone_ptr - zone(new posix_time_zone("MST-07")); -local_date_time - beg((ptime(date(2005,Jan,1),hours(0))), zone); -local_date_time - end((ptime(date(2005,Feb,1),hours(0))), zone); -local_time_period jan_mst(beg, end); - -local_date_time -ldt((ptime(date(2005,Jan,15),hours(12))), zone); -jan_mst.contains(ldt); // => true - -local_time_period zero(beg, beg); -zero.contains(beg); // false | |
bool contains(local_time_period) |
-True if period is within the period | -
// using jan_mst period from previous example - -local_date_time - beg((ptime(date(2005,Jan,7),hours(0))), zone); -local_time_period ltp(beg, hours(24)); - -jan_mst.contains(ltp); // => true | |
bool intersects(local_time_period) |
-True if periods overlap | -
// using jan_mst period from previous example - -local_date_time - beg((ptime(date(2005,Jan,7),hours(0))), zone); -local_date_time - end((ptime(date(2005,Feb,7),hours(0))), zone); -local_time_period ltp(beg, end); - -jan_mst.intersects(ltp); // => true | |
local_time_period intersection(local_time_period) |
-Calculate the intersection of 2 periods. Null if no intersection. | -
// using jan_mst period from previous example - -local_date_time - beg((ptime(date(2005,Jan,7),hours(0))), zone); -local_date_time - end((ptime(date(2005,Feb,7),hours(0))), zone); -local_time_period ltp(beg, end); - -local_time_period res(jan_mst.intersection(ltp)); -// res => 2005-Jan-07 00:00:00 through -// 2005-Jan-31 23:59:59.999999999 (inclusive) | |
local_time_period merge(local_time_period) |
-Returns union of two periods. Null if no intersection. | -
// using jan_mst period from previous example - -local_date_time - beg((ptime(date(2005,Jan,7),hours(0))), zone); -local_date_time - end((ptime(date(2005,Feb,7),hours(0))), zone); -local_time_period ltp(beg, end); - -local_time_period res(jan_mst.merge(ltp)); -// res => 2005-Jan-07 00:00:00 through -// 2005-Feb-06 23:59:59.999999999 (inclusive) | |
local_time_period span(local_time_period) |
-Combines two periods and any gap between them such that begin = min(p1.begin, p2.begin) and end = max(p1.end , p2.end). | -
// using jan_mst period from previous example - -local_date_time - beg((ptime(date(2005,Mar,1),hours(0))), zone); -local_date_time - end((ptime(date(2005,Apr,1),hours(0))), zone); -local_time_period mar_mst(beg, end); - -local_time_period res(jan_mst.span(mar_mst)); -// res => 2005-Jan-01 00:00:00 through -// 2005-Mar-31 23:59:59.999999999 (inclusive) | |
void shift(time_duration) |
-Add duration to both begin and end. | -
local_date_time - beg((ptime(date(2005,Mar,1),hours(0))), zone); -local_date_time - end((ptime(date(2005,Apr,1),hours(0))), zone); -local_time_period mar_mst(beg, end); - -mar_mst.shift(hours(48)); -// mar_mst => 2005-Mar-03 00:00:00 through -// 2005-Apr-02 23:59:59.999999999 (inclusive) |
Syntax | -Description | -
---|---|
Example | |
operator==, operator!= |
-Equality operators. Periods are equal if ltp1.begin == ltp2.begin && ltp1.last == ltp2.last | -
if (ltp1 == ltp2) {... | |
operator< |
-Ordering with no overlap. True if ltp1.end() less than ltp2.begin() | -
if (ltp1 < ltp2) {... | |
operator> |
-Ordering with no overlap. True if ltp1.begin() greater than ltp2.end() | -
if (ltp1 > ltp2) {... etc | |
operator<=, operator>= |
-Defined in terms of the other operators. | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Introduction -- - Usage Examples
-- 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. -
-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. | -
- 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. -
-#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-
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 |
Syntax | -Description | -
---|---|
Example | |
ptime time_from_string(std::string) |
-From delimited string. NOTE: Excess digits in fractional seconds will be dropped. Ex: "1:02:03.123456999" => 1:02:03.123456. This behavior is affected by the precision the library is compiled with (see Build-Compiler Information. | -
std::string ts("2002-01-20 23:59:59.000"); -ptime t(time_from_string(ts)) | |
ptime from_iso_string(std::string) |
-From non delimited iso form string. | -
std::string ts("20020131T235959"); -ptime t(from_iso_string(ts)) |
Syntax | -Description | -
---|---|
Example | |
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()); | |
ptime second_clock::universal_time() |
-Get the UTC time. | -
ptime t(second_clock::universal_time()) | |
ptime microsec_clock::local_time() |
-Get the local time using a sub second 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 achieved resolution. | -
ptime t(microsec_clock::local_time()); | |
ptime microsec_clock::universal_time() |
-Get the UTC time using a sub second 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 achieved resolution. | -
ptime t(microsec_clock::universal_time()); |
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); |
Syntax | -Description | -
---|---|
Example | |
date date() |
-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() |
-Get the time offset in the day. | -
date d(2002,Jan,10); -ptime t(d, hour(1)); -t.time_of_day() --> 01:00:00; | |
bool is_infinity() const |
-Returns true if ptime is either positive or negative infinity | -
ptime pt(pos_infin); -pt.is_infinity(); // --> true | |
bool is_neg_infinity() const |
-Returns true if ptime is negative infinity | -
ptime pt(neg_infin); -pt.is_neg_infinity(); // --> true | |
bool is_pos_infinity() const |
-Returns true if ptime is positive infinity | -
ptime pt(neg_infin); -pt.is_pos_infinity(); // --> true | |
bool is_not_a_date_time() const |
-Returns true if value is not a ptime | -
ptime pt(not_a_date_time); -pt.is_not_a_date_time(); // --> true | |
bool is_special() const |
-Returns true if ptime is any special_value
- |
-
ptime pt(pos_infin); -ptime pt2(not_a_date_time); -ptime pt3(date(2005,Mar,1), hours(10)); -pt.is_special(); // --> true -pt2.is_special(); // --> true -pt3.is_special(); // --> false |
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 |
Syntax | -Description | -
---|---|
Example | |
operator<<, operator>> |
-Streaming operators. Note: As of version 1.33, streaming operations have been greatly improved. See Date Time IO System for more details (including exceptions and error conditions). | -
ptime pt(not_a_date_time); -stringstream ss("2002-Jan-01 14:23:11"); -ss >> pt; -std::cout << pt; // "2002-Jan-01 14:23:11" - | |
operator==, operator!=, -operator>, operator<, -operator>=, operator<= |
-A full complement of comparison operators | -
t1 == t2, etc | |
ptime operator+(days) |
-Return a ptime adding a day offset | -
date d(2002,Jan,1); -ptime t(d,minutes(5)); -days dd(1); -ptime t2 = t + dd; | |
ptime operator-(days) |
-Return a ptime subtracting a day offset | -
date d(2002,Jan,1); -ptime t(d,minutes(5)); -days dd(1); -ptime t2 = t - dd; | |
ptime operator+(time_duration) |
-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) |
-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) |
-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 |
Functions for converting posix_time objects to, and from, tm
structs are provided as well as conversion from time_t
and FILETIME
.
Syntax | -Description | -
---|---|
Example | |
tm to_tm(ptime) |
-A function for converting a ptime object to a tm struct. The tm_isdst field is set to -1. |
-
ptime pt(date(2005,Jan,1), time_duration(1,2,3)); -tm pt_tm = to_tm(pt); -/* tm_year => 105 - tm_mon => 0 - tm_mday => 1 - tm_wday => 6 (Saturday) - tm_yday => 0 - tm_hour => 1 - tm_min => 2 - tm_sec => 3 - tm_isddst => -1 */ | |
date date_from_tm(tm datetm) |
-A function for converting a tm struct to a date object. The fields: tm_wday , tm_yday , and tm_isdst are ignored. |
-
tm pt_tm; -pt_tm.tm_year = 105; -pt_tm.tm_mon = 0; -pt_tm.tm_mday = 1; -pt_tm.tm_hour = 1; -pt_tm.tm_min = 2; -pt_tm.tm_sec = 3; -ptime pt = ptime_from_tm(pt_tm); -// pt => 2005-Jan-01 01:02:03 | |
tm to_tm(time_duration) |
-A function for converting a time_duration object to a tm struct. The fields: tm_year , tm_mon , tm_mday , tm_wday , tm_yday are set to zero. The tm_isdst field is set to -1. |
-
time_duration td(1,2,3); -tm td_tm = to_tm(td); -/* tm_year => 0 - tm_mon => 0 - tm_mday => 0 - tm_wday => 0 - tm_yday => 0 - tm_hour => 1 - tm_min => 2 - tm_sec => 3 - tm_isddst => -1 */ | |
ptime from_time_t(std::time_t) |
-Creates a ptime from the time_t parameter. The seconds held in the time_t are added to a time point of 1970-Jan-01. |
-
ptime pt(not_a_date_time); -std::time_t t; -t = 1118158776; -pt = from_time_t(t); -// pt => 2005-Jun-07 15:39:36 | |
ptime from_ftime<ptime>(FILETIME) |
-A template function that constructs a ptime from a FILETIME struct. |
-
FILETIME ft; -ft.dwHighDateTime = 29715317; -ft.dwLowDateTime = 3865122988UL; -ptime pt = from_ftime<ptime>(ft); -// pt => 2005-Jun-07 15:30:57.039582000 |
- 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 configure able 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) + nanoseconds(5); //01:00:00.000000005-
- Note that the existence of the higher resolution classes (eg: nanoseconds) depends on the installation of the library. See Build-Compiler Information for more information. -
-- Another way to handle this is to utilize the ticks_per_second() method of time_duration to - write code that is portable no matter how the library is compiled. The general equation - for calculating a resolution independent count is as follows: - -
--count*(time_duration_ticks_per_second / count_ticks_per_second) --
- - For example, let's suppose we want to construct using a count that represents tenths - of a second. That is, each tick is 0.1 second. -
--int number_of_tenths = 5; -//create a resolution independent count -- divide by 10 since there are -//10 tenths in a second. -int count = number_of_tenths*(time_duration::ticks_per_second()/10); -time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings --
#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-
Syntax | -Description | -
---|---|
Example | |
time_duration(hours, - minutes, - seconds, - fractional_seconds) |
-Construct a duration from the counts. The fractional_second parameter is a number of units and is therefore affected by the resolution the application is compiled with (see Build-Compiler Information). If the fractional_seconds argument exceeds the limit of the compiled precision, the excess value will be "carried over" into the seconds field. See above for techniques to creating a resolution independent count. | -
time_duration td(1,2,3,9); -//1 hr 2 min 3 sec 9 nanoseconds -time_duration td2(1,2,3,123456789); -time_duration td3(1,2,3,1000); -// with microsecond resolution (6 digits) -// td2 => "01:04:06.456789" -// td3 => "01:02:03.001000" -// with nanosecond resolution (9 digits) -// td2 => "01:02:03.123456789" -// td3 => "01:02:03.000001000" | |
time_duration(special_value sv) |
-Special values constructor. Important note: When a time_duration is a special value, either by construction or other means, the following accessor functions will give unpredictable results: hours(), minutes(), seconds(), ticks(), -fractional_seconds(), total_nanoseconds(), -total_microseconds(), total_milliseconds(), -total_seconds()The remaining accessor functions will work as expected. |
-
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); | |
milliseconds(long) |
-Number of milliseconds. | -
time_duration td = milliseconds(3); | |
microseconds(long) |
-Number of microseconds. | -
time_duration td = microseconds(3); | |
nanoseconds(long) |
-Number of nanoseconds. | -
time_duration td = nanoseconds(3); |
Syntax | -Description | -
---|---|
Example | |
time_duration duration_from_string(std::string) |
-From delimited string. NOTE: Excess digits in fractional seconds will be dropped. Ex: "1:02:03.123456999" => 1:02:03.123456. This behavior is affected by the precision the library is compiled with (see Build-Compiler Information. | -
std::string ts("23:59:59.000"); -time_duration td(duration_from_string(ts)); |
Syntax | -Description | -
---|---|
Example | |
long hours() |
-Get the number of normalized hours (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3); -time_duration neg_td(-1,2,3); -td.hours(); // --> 1 -neg_td.hours(); // --> -1 | |
long minutes() |
-Get the number of minutes normalized +/-(0..59) (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3); -time_duration neg_td(-1,2,3); -td.minutes(); // --> 2 -neg_td.minutes(); // --> -2 | |
long seconds() |
-Get the normalized number of second +/-(0..59) (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3); -time_duration neg_td(-1,2,3); -td.seconds(); // --> 3 -neg_td.seconds(); // --> -3 | |
long total_seconds() |
-Get the total number of seconds truncating any fractional seconds (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3,10); -td.total_seconds(); -// --> (1*3600) + (2*60) + 3 == 3723 | |
long total_milliseconds() |
-Get the total number of milliseconds truncating any remaining digits (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3,123456789); -td.total_milliseconds(); -// HMS --> (1*3600) + (2*60) + 3 == 3723 seconds -// milliseconds is 3 decimal places -// (3723 * 1000) + 123 == 3723123 | |
long total_microseconds() |
-Get the total number of microseconds truncating any remaining digits (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3,123456789); -td.total_microseconds(); -// HMS --> (1*3600) + (2*60) + 3 == 3723 seconds -// microseconds is 6 decimal places -// (3723 * 1000000) + 123456 == 3723123456 | |
long total_nanoseconds() |
-Get the total number of nanoseconds truncating any remaining digits (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3,123456789); -td.total_nanoseconds(); -// HMS --> (1*3600) + (2*60) + 3 == 3723 seconds -// nanoseconds is 9 decimal places -// (3723 * 1000000000) + 123456789 -// == 3723123456789 | |
long fractional_seconds() |
-Get the number of fractional seconds (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(1,2,3, 1000); -td.fractional_seconds(); // --> 1000 | |
bool is_negative() |
-True if duration is negative. | -
time_duration td(-1,0,0); -td.is_negative(); // --> true | |
time_duration invert_sign() |
-Generate a new duration with the sign inverted/ | -
time_duration td(-1,0,0); -td.invert_sign(); // --> 01:00:00 | |
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 | |
time_duration::num_fractional_digits() |
-Returns an unsigned short holding the number of fractional digits the time resolution has. | -
unsigned short secs; -secs = time_duration::num_fractional_digits(); -// 9 for nano, 6 for micro, etc. | |
time_duration::ticks_per_second() |
-Return the number of ticks in a second. For example, if the duration supports nanoseconds then the returned result will be 1000000. | -
std::cout << time_duration::ticks_per_second(); | |
boost::int64_t ticks() |
-Return the raw count of the duration type (will give unpredictable results if calling time_duration is a special_value ). |
-
time_duration td(0,0,0, 1000); -td.ticks() // --> 1000 | |
time_duration unit() |
-Return smallest possible unit of duration type (1 nanosecond). | -
time_duration::unit() --> time_duration(0,0,0,1) | |
bool is_neg_infinity() const |
-Returns true if time_duration is negative infinity | -
time_duration td(neg_infin); -td.is_neg_infinity(); // --> true | |
bool is_pos_infinity() const |
-Returns true if time_duration is positive infinity | -
time_duration td(neg_infin); -td.is_pos_infinity(); // --> true | |
bool is_not_a_date_time() const |
-Returns true if value is not a time | -
time_duration td(not_a_date_time); -td.is_not_a_date_time(); // --> true | |
bool is_special() const |
-Returns true if time_duration is any special_value
- |
-
time_duration td(pos_infin); -time_duration td2(not_a_date_time); -time_duration td3(2,5,10); -td.is_special(); // --> true -td2.is_special(); // --> true -td3.is_special(); // --> false |
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 |
Syntax | -Description | -
---|---|
Example | |
operator<<, operator>> |
-Streaming operators. Note: As of version 1.33, streaming operations have been greatly improved. See Date Time IO System for more details (including exceptions and error conditions). | -
time_duration td(0,0,0); -stringstream ss("14:23:11.345678"); -ss >> td; -std::cout << td; // "14:23:11.345678" - | |
operator==, operator!=, -operator>, operator<, -operator>=, operator<= |
-A full complement of comparison operators | -
dd1 == dd2, etc | |
time_duration operator+(time_duration) |
-Add durations. | -
time_duration td1(hours(1)+minutes(2)); -time_duration td2(seconds(10)); -time_duration td3 = td1 + td2; | |
time_duration operator-(time_duration) |
-Subtract durations. | -
time_duration td1(hours(1)+nanoseconds(2)); -time_duration td2 = td1 - minutes(1); | |
time_duration operator/(int) |
-Divide the length of a duration by an integer value. Discards any remainder. | -
hours(3)/2 == time_duration(1,30,0); -nanosecond(3)/2 == nanosecond(1); | |
time_duration operator*(int) |
-Multiply the length of a duration by an integer value. | -
hours(3)*2 == hours(6); |
Function for converting a time_duration to a tm
struct is provided.
Syntax | -Description | -
---|---|
Example | |
tm to_tm(time_duration) |
-A function for converting a time_duration object to a tm struct. The fields: tm_year , tm_mon , tm_mday , tm_wday , tm_yday are set to zero. The tm_isdst field is set to -1. |
-
time_duration td(1,2,3); -tm td_tm = to_tm(td); -/* tm_year => 0 - tm_mon => 0 - tm_mday => 0 - tm_wday => 0 - tm_yday => 0 - tm_hour => 1 - tm_min => 2 - tm_sec => 3 - tm_isddst => -1 */ |
- 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. -
-
- A period that is created with beginning and end points being equal, or with a duration of zero, is known as a zero length period. Zero length periods are considered invalid (it is perfectly legal to construct an invalid period). For these periods, the last
point will always be one unit less that the begin
point.
-
- The time periods example provides an example of using time periods. -
-#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-
Syntax | -Description | -
---|---|
Example | |
time_period(ptime, - ptime) |
-Create a period as [begin, end). If end is <= begin then the period will be defined as invalid. | -
date d(2002,Jan,01); -ptime t(d, seconds(10)); //10 sec after midnight -time_period tp(t, hours(3)); | |
time_period(ptime, - time_duration) |
-Create a period as [begin, begin+len) where end would be begin+len. If len is <= zero then the period will be defined as invalid. | -
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); |
Syntax | -Description | -
---|---|
Example | |
ptime begin() |
-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() |
-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() |
-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() |
-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() |
-True if period is not well formed. eg: end is less than or equal to begin. | -
date d(2002,Jan,01); -ptime t1(d, hours(12)); // noon on Jan 1st -ptime t2(d, hours(9)); // 9am on Jan 1st -time_period tp(t1, t2); -tp.is_null(); // true | |
bool contains(ptime) |
-True if ptime is within the period. Zero length periods cannot contain any points. | -
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 -time_period tp2(t1, t1); -tp2.contains(t1); // false | |
bool contains(time_period) |
-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) |
-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) |
-Calculate the intersection of 2 periods. Null if no intersection. | -
time_period merge(time_period) |
-Returns union of two periods. Null if no intersection. | -
time_period span(time_period) |
-Combines two periods and any gap between them such that begin = min(p1.begin, p2.begin) and end = max(p1.end , p2.end). | -
time_period shift(days) |
-Add duration to both begin and end. | -
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] -// string occupies one line |
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 and the fractional seconds are left out when zero. |
-
[2002-Jan-01 01:25:10.000000001/ \ - 2002-Jan-31 01:25:10.123456789] | |
operator>> |
-Input streaming operator for time duration. Uses facet to read [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 and the fractional seconds are left out when zero. |
-
[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. | -
- 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; - } - } --
#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-
Class | -Description | -
---|---|
Construction Parameters | |
time_iterator |
-Iterate incrementing by the specified duration. | -
ptime start_time, time_duration increment |
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. | -
time_duration td(1,2,3); -time_iterator titr(start_time, td); ---titr; // == start_time - 01:02:03 |
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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: -
-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 | -
ptime | -time_duration | -time_period | -
- No extra steps are required to build the date_time library for serialization use. -
-NOTE: due to a change in the serialization library interface, it is now required that all streamable objects be const prior to writing to the archive. The following template function will allow for this (and is used in the date_time tests). At this time no special steps are necessary to read from an archive. -
-- template<class archive_type, class temporal_type> - void save_to(archive_type& ar, const temporal_type& tt) - { - ar << tt; - } --
- 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); - save_to(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); - save_to(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-
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::day_calc_dst_rule — Canonical form for a class that provides day rule calculation.
-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 std::string start_rule_as_string() const; - virtual date_type end_day(year_type) const; - virtual std::string end_rule_as_string() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::day_clock — A clock providing day level services based on C time_t capabilities.
-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 &) ; - ::std::tm * get_universal_time(std::tm &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::day_functor — Functor to iterate a fixed number of days.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::days_before_weekday — Calculates the number of days since the previous weekday.
--template<typename date_type, typename weekday_type> - date_type::duration_type - days_before_weekday(const date_type & d, const weekday_type & wd);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::days_until_weekday — Calculates the number of days until the next weekday.
--template<typename date_type, typename weekday_type> - date_type::duration_type - days_until_weekday(const date_type & d, const weekday_type & wd);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::dst_calc_engine — Compile-time configurable daylight savings time calculation 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) ; -};
dst_calc_engine
public static functionstime_is_dst_result -local_is_dst(const date_type & d, const time_duration_type & td) ;-
Determines if the time is really in DST or not. Also checks for invalid and ambiguous. -
-bool is_dst_boundary_day(date_type d) ;
time_duration_type dst_offset() ;
date_type local_dst_start_day(year_type year) ;
date_type local_dst_end_day(year_type year) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::dst_calculator — Dynamic class used to caluclate dst transition information.
-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 &, const time_duration_type &, - const date_type &, const time_duration_type &, - const time_duration_type &) ; - 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) ; -};
dst_calculator
public static functionstime_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) ;-
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
-Number of minutes to adjust clock forward
Local day offset for start of dst
Time offset in the day for the local time
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) ;-
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
-Local time of day for end of dst
Time offset in the day for the local time
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, - const time_duration_type & dst_start_offset, - const date_type & dst_end_day, - const time_duration_type & dst_end_offset, - const time_duration_type & dst_length_minutes) ;-
Determines if the time is really in DST or not. Also checks for invalid and ambiguous. - -
-Parameters
-The day to check for dst
Ending day of dst for the given locality
Time offset within day given in dst for dst boundary
Starting day of dst for the given locality
Time offset within day for dst boundary
Time offset within the day to check
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) ;-
Determines if the time is really in DST or not. Also checks for invalid and ambiguous. - -
-Parameters
-The day to check for dst
Ending day of dst for the given locality
Offset within day given in dst for dst boundary (eg 120 for US which is 02:00:00)
Length of dst adjusment (eg: 60 for US)
Starting day of dst for the given locality
Offset within day for dst boundary (eg 120 for US which is 02:00:00)
Time offset within the day to check
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::dst_day_calc_rule — Defines base interface for calculating start and end date of daylight savings.
-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 std::string start_rule_as_string() const; - virtual date_type end_day(year_type) const; - virtual std::string end_rule_as_string() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::dst_not_valid —
--struct dst_not_valid { - // construct/copy/destruct - dst_not_valid(std::string = ""); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::duration_from_string — Creates a time_duration object from a delimited string.
--time_duration duration_from_string(const std::string & s);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::empty_formatter — Empty formatter.
--template<typename RangeT> unspecified empty_formatter(const RangeT & );
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ends_with — 'Ends with' predicate
--template<typename Range1T, typename Range2T, typename PredicateT> - bool ends_with(const Range1T & Input, const Range2T & Test, PredicateT Comp); -template<typename Range1T, typename Range2T> - bool ends_with(const Range1T & Input, const Range2T & Test);
This predicate holds when the test string 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
-An element comparison predicate
An input sequence
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::environment_iterator —
--class environment_iterator - : : public boost::eof_iterator< Derived, ValueType > -{ -public: - // construct/copy/destruct - environment_iterator(char **); - environment_iterator(); - - // public member functions - void get() ; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
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
private member functionsvoid increment() ;
bool equal(const eof_iterator & other) const;
const ValueType & dereference() const;
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::equals — 'Equals' predicate
--template<typename Range1T, typename Range2T, typename PredicateT> - bool equals(const Range1T & Input, const Range2T & Test, PredicateT Comp); -template<typename Range1T, typename Range2T> - bool equals(const Range1T & Input, const Range2T & Test);
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
-An element comparison predicate
An input sequence
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_all — Erase all algorithm.
--template<typename SequenceT, typename RangeT> - void erase_all(SequenceT & Input, const RangeT & Search);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_all_copy — Erase all algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_all_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search); -template<typename SequenceT, typename RangeT> - SequenceT erase_all_copy(const SequenceT & Input, const RangeT & Search);
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
-An input sequence
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_all_regex — Erase all regex algorithm.
--template<typename SequenceT, typename CharT, typename RegexTraitsT> - void erase_all_regex(SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_all_regex_copy — Erase all regex algorithm.
--template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT> - OutputIteratorT - erase_all_regex_copy(OutputIteratorT Output, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default); -template<typename SequenceT, typename CharT, typename RegexTraitsT> - SequenceT erase_all_regex_copy(const SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
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
-Regex options
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_first — Erase first algorithm.
--template<typename SequenceT, typename RangeT> - void erase_first(SequenceT & Input, const RangeT & Search);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_first_copy — Erase first algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_first_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search); -template<typename SequenceT, typename RangeT> - SequenceT erase_first_copy(const SequenceT & Input, const RangeT & Search);
Remove the first occurrence 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
-An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_head — Erase head algorithm.
--template<typename SequenceT> - void erase_head(SequenceT & Input, unsigned int N);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_head_copy — Erase head algorithm.
--template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - erase_head_copy(OutputIteratorT Output, const RangeT & Input, - unsigned int N); -template<typename SequenceT> - SequenceT erase_head_copy(const SequenceT & Input, unsigned int N);
Remove the head from the input. The head is a prefix of a sequence 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
-An input string
Length of the head
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_last — Erase last algorithm.
--template<typename SequenceT, typename RangeT> - void erase_last(SequenceT & Input, const RangeT & Search);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_last_copy — Erase last algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_last_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search); -template<typename SequenceT, typename RangeT> - SequenceT erase_last_copy(const SequenceT & Input, const RangeT & Search);
Remove the last occurrence 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
-An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_nth — Erase nth algorithm.
--template<typename SequenceT, typename RangeT> - void erase_nth(SequenceT & Input, const RangeT & Search, unsigned int Nth);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_nth_copy — Erase nth algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_nth_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, unsigned int Nth); -template<typename SequenceT, typename RangeT> - SequenceT erase_nth_copy(const SequenceT & Input, const RangeT & Search, - unsigned int Nth);
Remove the Nth occurrence 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
-An input string
An index of the match to be replaced. The index is 0-based.
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_range — Erase range algorithm.
--template<typename SequenceT> - void erase_range(SequenceT & Input, - const iterator_range< typename range_iterator< SequenceT >::type > & SearchRange);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_range_copy — Erase range algorithm.
--template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - erase_range_copy(OutputIteratorT Output, const RangeT & Input, - const iterator_range< typename range_const_iterator< RangeT >::type > & SearchRange); -template<typename SequenceT> - SequenceT erase_range_copy(const SequenceT & Input, - const iterator_range< typename range_const_iterator< SequenceT >::type > & SearchRange);
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
-An input sequence
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_regex — Erase regex algorithm.
--template<typename SequenceT, typename CharT, typename RegexTraitsT> - void erase_regex(SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_regex_copy — Erase regex algorithm.
--template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT> - OutputIteratorT - erase_regex_copy(OutputIteratorT Output, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default); -template<typename SequenceT, typename CharT, typename RegexTraitsT> - SequenceT erase_regex_copy(const SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
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
-Regex options
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_tail — Erase tail algorithm.
--template<typename SequenceT> - void erase_tail(SequenceT & Input, unsigned int N);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::erase_tail_copy — Erase tail algorithm.
--template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - erase_tail_copy(OutputIteratorT Output, const RangeT & Input, - unsigned int N); -template<typename SequenceT> - SequenceT erase_tail_copy(const SequenceT & Input, unsigned int N);
Remove the tail from the input. The tail is a suffix of a sequence 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
-An input string
Length of the head
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::error —
--class error { -public: - // construct/copy/destruct - error(const std::string &); - - // public member functions -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::eu_dst_trait — Rules for daylight savings start in the EU (Last Sun in Mar).
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find — Generic find algorithm.
--template<typename RangeT, typename FinderT> - iterator_range< typename range_result_iterator< RangeT >::type > - find(RangeT & Input, FinderT Finder);
Search the input using the given finder.
- -Parameters
-Finder object used for searching.
A string which will be searched.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either RangeT::iterator
or RangeT::const_iterator
, depending on the constness of the input parameter.
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_all — Find all algorithm.
--template<typename SequenceSequenceT, typename Range1T, typename Range2T> - SequenceSequenceT & - find_all(SequenceSequenceT & Result, Range1T & Input, - const Range2T & Search);
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
-A container which will be searched.
A container that can hold copies of references to the substrings
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_all_regex — Find all regex algorithm.
--template<typename SequenceSequenceT, typename RangeT, typename CharT, - typename RegexTraitsT> - SequenceSequenceT & - find_all_regex(SequenceSequenceT & Result, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
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
-Regex options
A container which will be searched.
A container that can hold copies of references to the substrings.
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_first — Find first algorithm.
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_first(Range1T & Input, const Range2T & Search);
Search for the first occurence of the substring in the input.
- -Parameters
-A string which will be searched.
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either RangeT::iterator
or RangeT::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_format — Generic replace algorithm.
--template<typename SequenceT, typename FinderT, typename FormatterT> - void find_format(SequenceT & Input, FinderT Finder, FormatterT Formatter);
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
-A Finder object used to search for a match to be replaced
A Formatter object used to format a match
An input sequence
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_format_all — Generic replace all algorithm.
--template<typename SequenceT, typename FinderT, typename FormatterT> - void find_format_all(SequenceT & Input, FinderT Finder, - FormatterT Formatter);
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
-A Finder object used to search for a match to be replaced
A Formatter object used to format a match
An input sequence
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_format_all_copy — Generic replace all algorithm.
--template<typename OutputIteratorT, typename RangeT, typename FinderT, - typename FormatterT> - OutputIteratorT - find_format_all_copy(OutputIteratorT Output, const RangeT & Input, - FinderT Finder, FormatterT Formatter); -template<typename SequenceT, typename FinderT, typename FormatterT> - SequenceT find_format_all_copy(const SequenceT & Input, FinderT Finder, - FormatterT Formatter);
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
-A Finder object used to search for a match to be replaced
A Formatter object used to format a match
An input sequence
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_format_copy — Generic replace algorithm.
--template<typename OutputIteratorT, typename RangeT, typename FinderT, - typename FormatterT> - OutputIteratorT - find_format_copy(OutputIteratorT Output, const RangeT & Input, - FinderT Finder, FormatterT Formatter); -template<typename SequenceT, typename FinderT, typename FormatterT> - SequenceT find_format_copy(const SequenceT & Input, FinderT Finder, - FormatterT Formatter);
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
-A Finder object used to search for a match to be replaced
A Formatter object used to format a match
An input sequence
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_head — Find head algorithm.
--template<typename RangeT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_head(RangeT & Input, unsigned int N);
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
-An input string
Length of the head
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_iterator — 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 RangeT> find_iterator(RangeT &, FinderT); - - // public member functions - bool eof() const; - - // private member functions - const match_type & dereference() const; - void increment() ; - bool equal(const find_iterator &) const; -};
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/destructfind_iterator();-
Construct null iterator. All null iterators are equal.
- -Postconditions: - - eof()==true
-find_iterator(const find_iterator & Other);-
Construct a copy of the find_iterator
-template<typename FinderT> - find_iterator(IteratorT Begin, IteratorT End, FinderT Finder);-
Construct new find_iterator for a given finder and a range.
-template<typename FinderT, typename RangeT> - find_iterator(RangeT & Col, FinderT Finder);-
Construct new find_iterator for a given finder and a range.
-find_iterator
private member functionsconst match_type & dereference() const;
void increment() ;
bool equal(const find_iterator & Other) const;
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_last — Find last algorithm.
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_last(Range1T & Input, const Range2T & Search);
Search for the last occurence of the substring in the input.
- -Parameters
-A string which will be searched.
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_nth — Find n-th algorithm.
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_nth(Range1T & Input, const Range2T & Search, unsigned int Nth);
Search for the n-th (zero-indexed) occurence of the substring in the input.
- -Parameters
-A string which will be searched.
An index (zero-indexed) of the match to be found.
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_regex — Find regex algorithm.
--template<typename RangeT, typename CharT, typename RegexTraitsT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_regex(RangeT & Input, const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
Search for a substring matching the given regex in the input.
- -Parameters
-Regex options
A container which will be searched.
A regular expression
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either RangeT::iterator
or RangeT::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_tail — Find tail algorithm.
--template<typename RangeT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_tail(RangeT & Input, unsigned int N);
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
-An input string
Length of the tail
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either RangeT::iterator
or RangeT::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::find_token — Find token algorithm.
--template<typename RangeT, typename PredicateT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_token(RangeT & Input, PredicateT Pred, - token_compress_mode_type eCompress = token_compress_off);
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
-A input string.
An unary predicate to identify a token
Enable/Disable compressing of adjacent tokens
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either RangeT::iterator
or RangeT::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::first_finder — "First" finder
--template<typename ContainerT> - unspecified first_finder(const ContainerT & Search); -template<typename ContainerT, typename PredicateT> - unspecified first_finder(const ContainerT & Search, PredicateT Comp);
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
-A substring to be searched for.
Returns:
-
- An instance of the first_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::first_kday_after — Calculate something like "First Sunday after Jan 1,2002.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::first_kday_before — Calculate something like "First Sunday before Jan 1,2002.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::first_kday_of_month — Useful generator functor for finding holidays and daylight savings.
-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; - virtual std::string to_string() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::first_last_rule_spec —
--struct first_last_rule_spec { - // types - typedef gregorian::date date_type; - typedef gregorian::first_kday_of_month start_rule; - typedef gregorian::last_kday_of_month end_rule; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::fixed_string_to_int — Helper function for parsing fixed length strings into integers.
--template<typename int_type, typename charT> - int_type fixed_string_to_int(std::istreambuf_iterator< charT > & itr, - std::istreambuf_iterator< charT > & stream_end, - parse_match_result< charT > & mr, - unsigned int length);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::format_date_parser — Class with generic date parsing using a format string.
-template<typename date_type, typename charT> -class format_date_parser { -public: - // types - typedef std::basic_string< charT > string_type; - typedef std::basic_stringstream< charT > stringstream_type; - typedef std::istreambuf_iterator< charT > stream_itr_type; - typedef string_type::const_iterator const_itr; - typedef date_type::year_type year_type; - typedef date_type::month_type month_type; - typedef date_type::day_type day_type; - typedef date_type::duration_type duration_type; - typedef date_type::day_of_week_type day_of_week_type; - typedef date_type::day_of_year_type day_of_year_type; - typedef string_parse_tree< charT > parse_tree_type; - typedef parse_tree_type::parse_match_result_type match_results; - typedef std::vector< std::basic_string< charT > > input_collection_type; - - // construct/copy/destruct - format_date_parser(const string_type &, const input_collection_type &, - const input_collection_type &, - const input_collection_type &, - const input_collection_type &); - format_date_parser(const string_type &, const std::locale &); - format_date_parser(const format_date_parser< date_type, charT > &); - - // public member functions - string_type format() const; - void format(string_type) ; - void short_month_names(const input_collection_type &) ; - void long_month_names(const input_collection_type &) ; - void short_weekday_names(const input_collection_type &) ; - void long_weekday_names(const input_collection_type &) ; - date_type parse_date(const string_type &, const string_type &, - const special_values_parser< date_type, charT > &) const; - date_type parse_date(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, - const special_values_parser< date_type, charT > &) const; - date_type parse_date(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type, - const special_values_parser< date_type, charT > &) const; - month_type parse_month(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type) const; - month_type parse_month(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type, - match_results &) const; - day_type parse_day_of_month(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &) const; - day_of_week_type - parse_weekday(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type) const; - day_of_week_type - parse_weekday(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type, - match_results &) const; - year_type parse_year(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type) const; - year_type parse_year(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, string_type, - match_results &) const; -};
The following is the set of recognized format specifiers
-a - Short weekday name
A - Long weekday name
b - Abbreviated month name
B - Full month name
d - Day of the month as decimal 01 to 31
j - Day of year as decimal from 001 to 366
m - Month name as a decimal 01 to 12
U - Week number 00 to 53 with first Sunday as the first day of week 1?
w - Weekday as decimal number 0 to 6 where Sunday == 0
W - Week number 00 to 53 where Monday is first day of week 1
x - facet default date representation
y - Year without the century - eg: 04 for 2004
Y - Year with century
The weekday specifiers (a and A) do not add to the date construction, but they provide a way to skip over the weekday names for formats that provide them.
-todo -- Another interesting feature that this approach could provide is an option to fill in any missing fields with the current values from the clock. So if you have m-%d the parser would detect the missing year value and fill it in using the clock.
-todo -- What to do with the x. x in the classic facet is just bad...
-format_date_parser
construct/copy/destructformat_date_parser(const string_type & format, - const input_collection_type & month_short_names, - const input_collection_type & month_long_names, - const input_collection_type & weekday_short_names, - const input_collection_type & weekday_long_names);
format_date_parser(const string_type & format, const std::locale & locale);
format_date_parser(const format_date_parser< date_type, charT > & fdp);
format_date_parser
public member functionsstring_type format() const;
void format(string_type format) ;
void short_month_names(const input_collection_type & month_names) ;
void long_month_names(const input_collection_type & month_names) ;
void short_weekday_names(const input_collection_type & weekday_names) ;
void long_weekday_names(const input_collection_type & weekday_names) ;
date_type parse_date(const string_type & value, const string_type & format, - const special_values_parser< date_type, charT > & sv_parser) const;
date_type parse_date(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - const special_values_parser< date_type, charT > & sv_parser) const;
date_type parse_date(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format, - const special_values_parser< date_type, charT > & sv_parser) const;-
Of all the objects that the format_date_parser can parse, only a date can be a special value. Therefore, only parse_date checks for special_values.
-month_type parse_month(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format) const;
month_type parse_month(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format, match_results & mr) const;
day_type parse_day_of_month(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end) const;
day_of_week_type -parse_weekday(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format) const;
day_of_week_type -parse_weekday(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format, match_results & mr) const;
year_type parse_year(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format) const;
year_type parse_year(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - string_type format, match_results & mr) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::from_ftime — Function to create a time object from an initialized FILETIME struct.
--template<typename time_type> time_type from_ftime(const FILETIME & ft);
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.
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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)
Table of Contents
- -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.
-Last revised: July 25, 2004 at 02:51:51 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-1. - | -Why can't I compare
- |
-
- |
- Comparison between
The problem occurs when the type of the function objects
- stored by both The most promising approach is to find a method of
- determining if
All of these problems translate into failures in the
- The other option is to place the burden on users that want
- to use |
-
-2. - | -I see void pointers; is this [mess] type safe? |
-
- | Yes, |
-
-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 int f(); -void g() { return f(); }- In essence, not using void returns allows
- |
-
-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 |
-
- |
- The cost of However, the performance of your application may benefit
- from or be disadvantaged by [Answer provided by Matt Hurd. See http://article.gmane.org/gmane.comp.lib.boost.devel/33278] - |
-
Last revised: February 18, 2004 at 06:37:13 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
Last revised: January 23, 2005 at 16:23:09 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
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 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.
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).
- 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.
-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.
-Last revised: March 12, 2003 at 23:27:22 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-
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>&); -}-
namespace boost { - template<typename F, typename G> bool function_equal(const F&, const G&); -}-
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Test | -Type | -Description | -If failing... | -
---|---|---|---|
- | run |
-Test the capabilities of the |
-The |
-
- | run |
-Test the capabilities of the |
-- |
- | run |
-Test the use of custom allocators. |
-Allocators are ignored by the implementation. |
-
- | 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. |
-
- | 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 |
-
- | run |
-Test the operation of the
- |
-- |
- | 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. |
-
- | run |
-Test the first tutorial example. |
-- |
- | run |
-Test the first tutorial example. |
-- |
- | run |
-Test the second tutorial example. |
-- |
- | run |
-Test the second tutorial example. |
-- |
- | run |
-Test member function example from tutorial. |
-- |
- | run |
-Test member function example from tutorial. |
-- |
- | run |
-Test standard binders example from tutorial. |
-- |
- | run |
-Test standard binders example from tutorial. |
-- |
- | run |
-Test |
-- |
- | run |
-Test |
-- |
Test | -Type | -Description | -If failing... | -
---|---|---|---|
- | compile-fail |
-Test the (incorrect!) use of comparisons between Boost.Function function objects. |
-Intuitive (but incorrect!) code may compile and will give meaningless results. |
-
- | compile-fail |
-Test the use of an incompatible function object with Boost.Function |
-Incorrect code may compile (with potentially unexpected results). |
-
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 | -
---|---|
|
-
|
-
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.
- 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 | -
---|---|
|
-
|
-
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 |
---|
|
Portable syntax |
---|
|
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,
-
-method will return whether or not the wrapper is empty. empty
()
Finally, we can clear out a function target by assigning it to 0
or by calling the
member function, e.g.,
-clear
()
f = 0;-
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.
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 | -
---|---|
|
-
|
-
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 | -
---|---|
|
-
|
-
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.
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; - |
-stateful_type a_function_object; - |
-
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.
-
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 either be
- EqualityComparable or have an overloaded boost::function_equal
). 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));
Last revised: March 18, 2005 at 04:54:32 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::functionN — A set of generalized function pointers that can be used for callbacks or wrapping function objects.
-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>&);
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/destructfunctionN();-
Postconditions:
-
- this->empty()
Throws:
-
- Will not throw.
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.
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.
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.
~functionN();-
Effects:
-
- If !this->empty()
, destroys the target of this.
functionN
capacitybool empty() const;-
Returns:
-
- false
if this
has a target, and true
otherwise.
Throws:
-
- Will not throw.
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.
bool operator!() const;-
Returns:
-
- this->empty()
Throws:
-
- Will not throw.
functionN
target accesstemplate<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.
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
invocationresult_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
comparison operatorstemplate<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)
.functionN
- objects are not
- EqualityComparable.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.
-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)
.functionN
- objects are not
- EqualityComparable.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.
-- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::function_base — The common base class for all Boost.Function - objects. Objects of type function_base may not be created - directly.
--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; -};
function_base
target accesstemplate<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.
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)
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::function_equal —
Compare two function objects for equality.
--template<typename F, typename G> bool function_equal(const F& f, const G& g);
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::gather_month_strings — This function gathers up all the month strings from a std::locale.
--template<typename charT> - std::vector< std::basic_string< charT > > - gather_month_strings(const std::locale & locale, bool short_strings = true);
Using the time_put facet, this function creates a collection of all the month strings from a locale. This is handy when building custom date parsers or formatters that need to be localized.
- -Parameters
-The locale to use when gathering the strings
True(default) to gather short strings, false for long strings.
Returns: - - A vector of strings containing the strings in order. eg: Jan, Feb, Mar, etc.
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::gather_weekday_strings — This function gathers up all the weekday strings from a std::locale.
--template<typename charT> - std::vector< std::basic_string< charT > > - gather_weekday_strings(const std::locale & locale, - bool short_strings = true);
Using the time_put facet, this function creates a collection of all the weekday strings from a locale starting with the string for 'Sunday'. This is handy when building custom date parsers or formatters that need to be localized.
- -Parameters
-The locale to use when gathering the strings
True(default) to gather short strings, false for long strings.
Returns: - - A vector of strings containing the weekdays in order. eg: Sun, Mon, Tue, Wed, Thu, Fri, Sat
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-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);
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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_day — Represent a day of the month (range 1 - 31).
--class greg_day { -public: - // construct/copy/destruct - greg_day(unsigned short); - - // public member functions - unsigned short as_number() const; - operator unsigned short() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_durations_config — config struct for additional duration types (ie months_duration<> & years_duration<>)
--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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_facet_config — Configuration of the output facet template.
--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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_month — Wrapper class to represent months in gregorian based calendar.
--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() ; -};
greg_month
public member functionsoperator 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;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_weekday — Represent a day within a week (range 0==Sun to 6==Sat).
--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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::greg_year — Represent a day of the month (range 1900 - 10000).
--class greg_year { -public: - // construct/copy/destruct - greg_year(unsigned short); - - // public member functions - operator unsigned short() const; -};
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.
- - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::gregorian_calendar — Gregorian calendar for this implementation, hard work in the base.
--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. -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::gregorian_calendar_base — An implementation of the Gregorian calendar.
-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() ; -};
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 functionsunsigned short day_of_week(const ymd_type & ymd) ;
int week_number(const ymd_type & ymd) ;
date_int_type day_number(const ymd_type & ymd) ;
date_int_type julian_day_number(const ymd_type & ymd) ;
long modjulian_day_number(const ymd_type & ymd) ;
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 y, month_type m) ;
ymd_type epoch() ;
unsigned short days_in_week() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::has_const_time_erase — Const time erase trait.
-template<typename T> -class has_const_time_erase { -public: - // types - typedef mpl::bool_< has_const_time_erase< T >::value > type; - - static const bool value; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::has_const_time_insert — Const time insert trait.
-template<typename T> -class has_const_time_insert { -public: - // types - typedef mpl::bool_< has_const_time_insert< T >::value > type; - - static const bool value; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::has_native_replace — Native replace trait.
-template<typename T> -class has_native_replace { -public: - // types - typedef mpl::bool_< has_native_replace< T >::value > type; - - static const bool value; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::has_stable_iterators — Stable iterators trait.
-template<typename T> -class has_stable_iterators { -public: - // types - typedef mpl::bool_< has_stable_iterators< T >::value > type; - - static const bool value; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2005 Daniel James
- 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 - ) - -
-Table of Contents
- -boost::hash
is an implementation of the hash function object
-specified by the Technical Report. It is intended for use as the default hash function
-for unordered associative containers, and the Boost Multi-Index Containers Library's hash indexes.
-As it is compliant with the Technical Report, it will work with:
--It also implements the extension proposed by Peter Dimov in issue 6.18 of the -Library Extension Technical Report Issues List, this adds support for:
-std::pair
boost::hash
for custom types.
-Last revised: July 31, 2005 at 15:55:26 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-This library is based on the design by Peter Dimov. During the inital development -Joaquín M López Muñoz made many useful suggestions and contributed fixes.
--The review was managed by Thorsten Ottosen, and the library reviewed by: -David Abrahams, Alberto Barbati, Topher Cooper, Caleb Epstein, Dave Harris, -Chris Jefferson, Bronek Kozicki, John Maddock, Tobias Swinger,Jaap Suter -and Rob Stewart.
-
-The implementation of the hash function for pointers is based on suggestions
-made by Alberto Barbati and Dave Harris. Dave Harris also suggested an
-important improvement to boost::hash_combine
that was taken up.
-The original implementation came from Jeremy B. Maitin-Shepard's hash table -library, although this is a complete rewrite.
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Say you have a point class, representing a two dimensional location:
-class point
-{
- int x;
- int y;
-public:
- point() : x(0), y(0) {}
- point(int x, int y) : x(x), y(y) {}
-
- bool operator==(point const& other) const
- {
- return x = other.x && y == other.y;
- }
-};
-
-and you wish to use it as the key for an unordered_map
. You need to
-customise the hash for this structure. To do this we need to combine
-the hash values for x
and y
. The function
-boost::hash_combine
is supplied for this purpose:
class point
-{
- ...
-
- friend std::size_t hash_value(point const& p)
- {
- std::size_t seed = 0;
- boost::hash_combine
(seed, p.x);
- boost::hash_combine
(seed, p.y);
-
- return seed;
- }
-
- ...
-};
-
-Calls to hash_combine incrementally build the hash from the different members
-of point, it can be repeatedly called for any number of elements. It calls
-hash_value
on the supplied element, and combines it with the seed.
-Full code for this example is at -/libs/functional/hash/examples/point.cpp.
-
-When using __hash_combine the order of the
-calls matters.
-- std::size_t seed = 0; - boost::hash_combine(seed, 1); - boost::hash_combine(seed, 2); --results in a different seed to: - - std::size_t seed = 0; - boost::hash_combine(seed, 2); - boost::hash_combine(seed, 1); --If you are calculating a hash value for data where the order of the data -doesn't matter in comparisons (e.g. a set) you will have to ensure that the -data is always supplied in the same order. - - |
-To calculate the hash of an iterator range you can use boost::hash_range
:
std::vector<std::string> some_strings;
-std::size_t hash = boost::hash_range
(some_strings.begin(), some_strings.end());
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash
is implemented by calling the function hash_value
.
-The namespace isn't specified so that it can detect overloads via argument
-dependant lookup. So if there is a free function hash_value
in the same
-namespace as a custom type, it will get called.
-If you have a structure library::book
, where each book
is uniquely
-defined by it's member id
:
namespace library
-{
- struct book
- {
- int id;
- std::string author;
- std::string title;
-
- // ....
- };
-
- bool operator==(book const& a, book const& b)
- {
- return a.id == b.id;
- }
-}
-
-Then all you would need to do is write the function library::hash_value
:
namespace library
-{
- std::size_t hash_value(book const& b)
- {
- boost::hash
<int> hasher;
- return hasher(b.id);
- }
-}
-
-And you can now use boost::hash
with book:
library::book knife(3458, "Zane Grey", "The Hash Knife Outfit");
-library::book dandelion(1354, "Paul J. Shanley",
- "Hash & Dandelion Greens");boost::hash
<library::book> book_hasher;
-std::size_t knife_hash_value = book_hasher(knife);
-
-// If std::unordered_set is available:
-std::unordered_set<library::book, boost::hash
<library::book> > books;
-books.insert(knife);
-books.insert(library::book(2443, "Lindgren, Torgny", "Hash"));
-books.insert(library::book(1953, "Snyder, Bernadette M.",
- "Heavenly Hash: A Tasty Mix of a Mother's Meditations"));
-
-assert(books.find(knife) != books.end());
-assert(books.find(dandelion) == books.end());
--The full example can be found in: -/libs/functional/hash/examples/books.hpp -and -/libs/functional/hash/examples/books.cpp.
--When writing a hash function, first look at how the equality function works. -Objects that are equal must generate the same hash value. -When objects are not equal the should generate different hash values. -In this object equality was based just on the id, if it was based -on the objects name and author the hash function should take them into account -(how to do this is discussed in the next section). - |
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
A Proposal to Add Hash Tables to the Standard Library
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1456.html
-
-The hash table proposal explains much of the design. The hash function object
-is discussed in Section D.
The C++ Standard Library Technical Report.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1745.pdf
-
-Contains the hash function specification in section 6.3.2.
Library Extension Technical Report Issues List.
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf
-
-The library implements the extension described in Issue 6.18.
Methods for Identifying Versioned and Plagiarised Documents
-
-Timothy C. Hoad, Justin Zobel
http://www.cs.rmit.edu.au/~jz/fulltext/jasist-tch.pdf
-
-Contains the hash function that boost::hash_combine
is based on.
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash
is written to be as portable as possible, but unfortunately, several
-older compilers don't support argument dependent lookup (ADL) - the mechanism
-used for customization. On those compilers custom overloads for hash_value
-need to be declared in the boost namespace.
-On a strictly standards compliant compiler, an overload defined in the
-boost namespace won't be found when boost::hash
is instantiated,
-so for these compilers the overload should only be declared in the same
-namespace as the class.
-Let's say we have a simple custom type:
-namespace foo
-{
- struct custom_type
- {
- int value;
-
- friend inline std::size_t hash_value(custom_type x)
- {
- boost::hash
<int> hasher;
- return hasher(x.value);
- }
- };
-}
-
-On a compliant compiler, when hash_value
is called for this type,
-it will look at the namespace inside the type and find hash_value
-but on a compiler which doesn't support ADL hash_value
won't be found.
-So on these compilers define a member function:
-#ifndef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
- friend inline std::size_t hash_value(custom_type x)
- {
- boost::hash
<int> hasher;
- return hasher(x.value);
- }
-#else
- std::size_t hash() const
- {
- boost::hash
<int> hasher;
- return hasher(value);
- }
-#endif
-
-which will be called from the boost
namespace:
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
-namespace boost
-{
- std::size_t hash_value(foo::custom_type x)
- {
- return x.hash();
- }
-}
-#endif
--Full code for this example is at -/libs/functional/hash/examples/portable.cpp.
-
-On Visual C++ versions 6.5 and 7.0, hash_value
isn't overloaded for built in
-arrays. boost::hash
, boost::hash_combine
and boost::hash_range
all use a workaround to
-support built in arrays so this shouldn't be a problem in most cases.
-On Visual C++ versions 6.5 and 7.0, function pointers aren't currently supported.
-boost::hash_value(long double)
on GCC on Solaris appears to treat
-long double
s as doubles - so the hash function doesn't take into account the
-full range of values.
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
For the full specification, see section 6.3 of the - C++ Standard Library Technical Report - and issue 6.18 of the - Library Extension Technical Report Issues List. -
-Includes all the following headers.
-
- Defines boost::hash
,
- the implementation for built in types and
- std::string
and customisation functions.
-
namespace boost { - template<typename T> struct hash; - template<typename T> void hash_combine(size_t &, T const &); - template<typename It> std::size_t hash_range(It, It); - template<typename It> void hash_range(std::size_t&, It, It); - std::size_t hash_value(int); - std::size_t hash_value(unsigned int); - std::size_t hash_value(long); - std::size_t hash_value(unsigned long); - std::size_t hash_value(float); - std::size_t hash_value(double); - std::size_t hash_value(long double); - template<typename T> std::size_t hash_value(T* const&); - template<typename T, unsigned N> std::size_t hash_value(T (&val)[N]); - template<typename T, unsigned N> std::size_t hash_value(const T (&val)[N]); - template<typename Ch, typename A> - std::size_t hash_value(std::basic_string<Ch, std::char_traits<Ch>, A> const&); -}-
- Hash implementation for std::pair
.
-
namespace boost { - template<typename A, typename B> - std::size_t hash_value(std::pair<A, B> const &); -}-
- Hash implementation for std::vector
.
-
namespace boost { - template<typename T, typename A> - std::size_t hash_value(std::vector<T, A> const &); -}-
- Hash implementation for std::list
.
-
namespace boost { - template<typename T, typename A> - std::size_t hash_value(std::list<T, A> const &); -}-
- Hash implementation for std::deque
.
-
namespace boost { - template<typename T, typename A> - std::size_t hash_value(std::deque<T, A> const &); -}-
- Hash implementation for std::set
and std::multiset
.
-
namespace boost { - template<typename K, typename C, typename A> - std::size_t hash_value(std::set<K, C, A> const &); - template<typename K, typename C, typename A> - std::size_t hash_value(std::multiset<K, C, A> const &); -}-
- Hash implementation for std::map
and std::multimap
.
-
namespace boost { - template<typename K, typename T, typename C, typename A> - std::size_t hash_value(std::map<K, T, C, A> const &); - template<typename K, typename T, typename C, typename A> - std::size_t hash_value(std::multimap<K, T, C, A> const &); -}-
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-When using a hash index with Boost.MultiIndex, you don't need to do
-anything to use boost::hash
as it uses it by default.
-To find out how to use a user-defined type, read the
-section on extending boost::hash for a custom data type.
-If your standard library supplies its own implementation of the unordered
-associative containers and you wish to use
-boost::hash
, just use an extra template parameter:
std::unordered_multiset<std::vector<int>, boost::hash
<int> >
- set_of_ints;
-
-std::unordered_set<std::pair<int, int>, boost::hash
<std::pair<int, int> >
- set_of_pairs;
-
-std::unordered_map<int, std::string, boost::hash
<int> > map_int_to_string;
-
-To use boost::hash
directly, create an instance and call it as a function:
#include <boost/hash/hash.hpp>
-
-int main()
-{
- boost::hash
<std::string> string_hash;
-
- std::size_t h = string_hash("Hash me");
-}
--If you wish to make use of the extensions, you will need to include the -appropriate header (see the -reference documentation for the full list).
-#include <boost/hash/pair.hpp>
-
-int main()
-{
- boost::hash
<std::pair<int, int> > pair_hash;
-
- std::size_t h = pair_hash(std::make_pair(1, 2));
-}
-
-Or alternatively, include <boost/hash.hpp>
for the full library.
-For an example of generic use, here is a function to generate a vector -containing the hashes of the elements of a container:
-template <class Container>
-std::vector<std::size_t> get_hashes(Container const& x)
-{
- std::vector<std::size_t> hashes;
- std::transform(x.begin(), x.end(), std::insert_iterator(hashes),
- boost::hash
<typename Container::value_type>());
-
- return hashes;
-}
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_combine — - Called repeatedly to incrementally create a hash value from - several variables. -
--template<typename T> void hash_combine(size_t & seed, T const & v);
Effects: - -
seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_range — - Calculate the combined hash value of the elements of an iterator - range. -
--template<typename It> std::size_t hash_range(It first, It last); -template<typename It> void hash_range(std::size_t& seed, It first, It last);
Effects: - - For the two argument overload: -
-size_t seed = 0; - -for(; first != last; ++first) -{ - hash_combine(seed, *first); -} - -return seed; -For the three arguments overload: -
-for(; first != last; ++first) -{ - hash_combine(seed, *first); -} -
hash_range
is sensitive to the order of the elements
- so it wouldn't be appropriate to use this with an unordered
- container.
- This is an extension to TR1
hash_value(std::iterator_traits<It>::value_type)
- throws. hash_range(std::size_t&, It, It)
has basic exception safety as long as
- hash_value(std::iterator_traits<It>::value_type)
- has basic exception safety.
-
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::head_finder — "Head" finder
--unspecified head_finder(unsigned int N);
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
-The size of the head
Returns:
-
- An instance of the head_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::hours — Allows expression of durations as an hour count.
--class hours : public boost::posix_time::time_duration { -public: - // construct/copy/destruct - hours(long); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::icontains — 'Contains' predicate ( case insensitive )
--template<typename Range1T, typename Range2T> - bool icontains(const Range1T & Input, const Range2T & Test, - const std::locale & Loc = std::locale());
This predicate holds when the test container is contained in the Input. Elements are compared case insensitively.
- -Parameters
-An input sequence
A locale used for case insensitive comparison
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename T, typename A> - std::size_t hash_value(std::vector<T, A> const & val);
Returns:
-
- hash_range(val.begin(), val.end());
Throws:
-
-
- Only throws if hash_value(T)
throws.
-
Notes:
-
- This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value — - Implementation of a hash function for pointers. -
--template<typename T> std::size_t hash_value(T* const& val);
- Generally shouldn't be called directly by users, instead they should use
- boost::hash
, boost::hash_range
- or boost::hash_combine
which
- call hash_value without namespace qualification so that overloads
- for custom types are found via ADL.
-
Notes: - - Overloads for other types supplied in other headers.
This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
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 functionsbasic_parsed_options(const basic_parsed_options< char > & po) ;-
Constructs wrapped options from options in UTF8 encoding.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_time_period_formatter — Put a time period into a stream using appropriate facets.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::parse_delimited_time_duration — Creates a time_duration object from a delimited string.
--template<typename time_duration> - time_duration parse_delimited_time_duration(const std::string & s);
Expected format for string is "[-]h[h][:mm][:ss][.fff]". If the number of fractional digits provided is greater than the precision of the time duration type then the extra digits are truncated.
-A negative duration will be created if the first character in string is a '-', all other '-' will be treated as delimiters. Accepted delimiters are "-:,.".
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_resolution_traits_bi32_impl — traits struct for time_resolution_traits implementation type
--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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_resolution_traits_adapted32_impl — traits struct for time_resolution_traits implementation type
--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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_resolution_traits_bi64_impl — traits struct for time_resolution_traits implementation type
--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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_resolution_traits_adapted64_impl — traits struct for time_resolution_traits implementation type
--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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::parse_environment —
--BOOST_PROGRAM_OPTIONS_DECL parsed_options -parse_environment(const options_description & , - const function1< std::string, std::string > & name_mapper);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::operator<< — ostream operator for gregorian::date
--template<typename charT, typename traits> - std::basic_ostream< charT, traits > & - operator<<(std::basic_ostream< charT, traits > & os, const date & d);
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)
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator+= —
--local_date_time -operator+=(local_date_time & t, const boost::gregorian::months & m);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value — - Implementation of a hash function for integers. -
--std::size_t hash_value(int val); -std::size_t hash_value(unsigned int val); -std::size_t hash_value(long val); -std::size_t hash_value(unsigned long val);
- Generally shouldn't be called directly by users, instead they should use
- boost::hash
, boost::hash_range
- or boost::hash_combine
which
- call hash_value without namespace qualification so that overloads
- for custom types are found via ADL.
-
Notes: - - Overloads for other types supplied in other headers.
This is an extension to TR1
val
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::iso_format_base<wchar_t> — Class to provide common iso formatting spec.
--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() ; -};
iso_format_base
public static functionsmonth_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 sep) ;
bool is_fractional_time_sep(wchar_t sep) ;
bool is_timezone_sep(wchar_t sep) ;
wchar_t element_sep_char() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename T, typename A> - std::size_t hash_value(std::list<T, A> const & val);
Returns:
-
- hash_range(val.begin(), val.end());
Throws:
-
-
- Only throws if hash_value(T)
throws.
-
Notes:
-
- This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename T, typename A> - std::size_t hash_value(std::deque<T, A> const & val);
Returns:
-
- hash_range(val.begin(), val.end());
Throws:
-
-
- Only throws if hash_value(T)
throws.
-
Notes:
-
- This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value — - Implementation of a hash function for built in arrays. -
--template<typename T, unsigned N> std::size_t hash_value(T (&val)[N] ); -template<typename T, unsigned N> std::size_t hash_value(const T (&val)[N] );
- Generally shouldn't be called directly by users, instead they should use
- boost::hash
, boost::hash_range
- or boost::hash_combine
which
- call hash_value without namespace qualification so that overloads
- for custom types are found via ADL.
-
Notes: - - Overloads for other types supplied in other headers.
This is an extension to TR1
hash_range(val, val+N)
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::dynamic_local_time_adjustor — Allow sliding utc adjustment with fixed dst rules.
-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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator- —
--local_date_time -operator-(const local_date_time & t, const boost::gregorian::years & y);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::operator&& — predicate 'and' composition predicate
--template<typename Pred1T, typename Pred2T> - unspecified operator&&(const predicate_facade< Pred1T > & Pred1, - const predicate_facade< Pred2T > & Pred2);
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
-The first predicate
The second predicate
Returns:
-
- An instance of the class_and
predicate
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator&& — Computes the logical conjuction of two tribools.
--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 );
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 | -
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 *) ; -};
Class which provides convenient creation syntax to option_description.
-options_description_easy_init
construct/copy/destructoptions_description_easy_init(options_description * owner);
options_description_easy_init
public member functionsoptions_description_easy_init & -operator()(const char * name, const char * description) ;
options_description_easy_init & -operator()(const char * name, const value_semantic * s) ;
options_description_easy_init & -operator()(const char * name, const value_semantic * s, - const char * description) ;
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::store —
--BOOST_PROGRAM_OPTIONS_DECL void -store(const basic_parsed_options< char > & options, variables_map & m, - bool utf8 = false);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::regex_finder — "Regex" finder
--template<typename CharT, typename RegexTraitsT> - unspecified regex_finder(const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type MatchFlags = match_default);
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
-Regex search options
A regular expression
Returns:
-
- An instance of the regex_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator-= —
--local_date_time -operator-=(local_date_time & t, const boost::gregorian::years & y);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::value_semantic_codecvt_helper —
-template<typename charT> -class value_semantic_codecvt_helper { -public: -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::read_write_scheduling_policy::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.
-
-enum read_write_scheduling_policy { writer_priority, reader_priority,
- alternating_many_reads,
- alternating_single_read };
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::make_recursive_variant_over —
Exposes a recursive variant
whose bounded types
- are the elements of the given type sequence.
template<typename Sequence> -class make_recursive_variant_over { -public: - // types - typedef variant< unspecified > type; -};
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.make_recursive_variant_over
may not be supported on
- your compiler. See
- BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
- for more information.- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::regex_formatter — 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);
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
-Format flags
Regex format definition
Returns:
-
- An instance of the regex_formatter
functor
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::token_compress_mode_type — Token compression mode.
-
-enum token_compress_mode_type { token_compress_on, token_compress_off };
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::operator<< — Provides streaming output for variant
types.
-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);
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
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::operator|| — predicate 'or' composition predicate
--template<typename Pred1T, typename Pred2T> - unspecified operator||(const predicate_facade< Pred1T > & Pred1, - const predicate_facade< Pred2T > & Pred2);
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
-The first predicate
The second predicate
Returns:
-
- An instance of the class_or
predicate
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_VARIANT_NO_REFERENCE_SUPPORT —
Indicates variant
does not
- support references as bounded types.
BOOST_VARIANT_NO_REFERENCE_SUPPORT
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator!= — Compare tribools for inequality.
--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 );
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 | -
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::get_default_indeterminate_name — Returns a string containing the default name for the indeterminate value of a tribool with the given character type T.
--template<typename T> std::basic_string< T > get_default_indeterminate_name();
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator<< — Writes the value of a tribool to a stream.
--template<typename CharT, typename Traits> - std::basic_ostream< CharT, Traits > & - operator<<(std::basic_ostream< CharT, Traits > & out, tribool x);
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
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator<< — Writes the indeterminate tribool value to a stream.
--template<typename CharT, typename Traits> - std::basic_ostream< CharT, Traits > & - operator<<(std::basic_ostream< CharT, Traits > & out, unspecified );
This routine 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
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator>> — Reads a tribool value from a stream.
--template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > & in, tribool & x);
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
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
Defined only if
- make_variant_over
and
- make_recursive_variant_over
- are not supported for some reason on the target compiler.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator-= —
--local_date_time -operator-=(local_date_time & t, const boost::gregorian::months & m);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
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
public member functionsvoid 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'.
-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.
-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()
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::regex_finder — "Regex" finder
--template<typename CharT, typename RegexTraitsT> - unspecified regex_finder(const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type MatchFlags = match_default);
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
-Regex search options
A regular expression
Returns:
-
- An instance of the regex_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_VARIANT_ENUM_SHIFTED_PARAMS —
Enumerate all but the first parameter for use with
- variant
.
BOOST_VARIANT_ENUM_SHIFTED_PARAMS(param)
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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT —
Indicates
- make_recursive_variant
operates in
- an implementation-defined manner.
BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
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.)
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::operator! — predicate negation operator
--template<typename PredT> - unspecified operator!(const predicate_facade< PredT > & Pred);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::split — Split algorithm.
--template<typename SequenceSequenceT, typename RangeT, typename PredicateT> - SequenceSequenceT & - split(SequenceSequenceT & Result, RangeT & Input, PredicateT Pred, - token_compress_mode_type eCompress = token_compress_off);
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
-A container which will be searched.
A predicate to identify separators. This predicate is supposed to return true if a given element is a separator.
A container that can hold copies of references to the substrings
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator|| — Computes the logical disjunction of two tribools.
--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 );
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 | -
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::operator<< — operator<< for gregorian::date_period typical output: [2002-Jan-01/2002-Jan-31]
--template<typename charT, typename traits> - std::basic_ostream< charT, traits > & - operator<<(std::basic_ostream< charT, traits > & os, const date_period & dp);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator- —
--local_date_time -operator-(const local_date_time & t, const boost::gregorian::months & m);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 };
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value — - Implementation of a hash function for floating point values. -
--std::size_t hash_value(float val); -std::size_t hash_value(double val); -std::size_t hash_value(long double val);
- Generally shouldn't be called directly by users, instead they should use
- boost::hash
, boost::hash_range
- or boost::hash_combine
which
- call hash_value without namespace qualification so that overloads
- for custom types are found via ADL.
-
Notes: - - Overloads for other types supplied in other headers.
This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_duration — Represents some amount of elapsed time measure to a given resolution.
-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) const; - 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 -};
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/destructtime_duration();
time_duration(hour_type hours, min_type minutes, sec_type seconds = 0, - fractional_seconds_type frac_sec = 0);
time_duration(const time_duration< T, rep_type > & other);
time_duration(special_values sv);
time_duration(impl_type in);
time_duration
public member functionshour_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 & rhs) const;
bool operator==(const time_duration & rhs) const;
duration_type operator-() const;
duration_type operator-(const duration_type & d) const;
duration_type operator+(const duration_type & d) const;
duration_type operator/(int divisor) const;
duration_type operator-=(const duration_type & d) ;
duration_type operator+=(const duration_type & d) ;
duration_type operator/=(int divisor) ;
duration_type operator *(int rhs) const;
duration_type operator *=(int divisor) ;
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;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
BOOST_PROGRAM_OPTIONS_VERSION —
-BOOST_PROGRAM_OPTIONS_VERSION
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::store —
--BOOST_PROGRAM_OPTIONS_DECL void -store(const basic_parsed_options< wchar_t > & options, variables_map & m);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_time_duration_formatter — Put a time type into a stream using appropriate facets.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator+ —
--local_date_time -operator+(const local_date_time & t, const boost::gregorian::months & m);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator! — Computes the logical negation of a tribool.
-- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::xtime_clock_types —
Specifies the clock type to use when creating - an object of type xtime.
-
-enum xtime_clock_types { TIME_UTC };
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::regex_formatter — 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);
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
-Format flags
Regex format definition
Returns:
-
- An instance of the regex_formatter
functor
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename K, typename T, typename C, typename A> - std::size_t hash_value(std::map<K, T, C, A> const & val); -template<typename K, typename T, typename C, typename A> - std::size_t hash_value(std::multimap<K, T, C, A> const & val);
Returns:
-
- hash_range(val.begin(), val.end());
Throws:
-
-
- Only throws if
- hash_value(std::pair<K const, T>)
- throws.
-
Notes:
-
- This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::simple_format<wchar_t> — Specialization of formmating rules for 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() ; -};
simple_format
public static functionsconst 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() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::dst_adjustment_offsets — Structure which holds the time offsets associated with daylight savings time.
-template<typename time_duration_type> -class dst_adjustment_offsets { -public: - // construct/copy/destruct - dst_adjustment_offsets(const time_duration_type &, - const time_duration_type &, - const time_duration_type &); - - // public member functions - - time_duration_type dst_adjust_; - time_duration_type dst_start_offset_; - time_duration_type dst_end_offset_; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
- Implementation of a hash function for std::basic_string
.
-
-template<typename Ch, typename A> - std::size_t hash_value(std::basic_string<Ch, std::char_traits<Ch>, A> const& val);
- Generally shouldn't be called directly by users, instead they should use
- boost::hash
, boost::hash_range
- or boost::hash_combine
which
- call hash_value without namespace qualification so that overloads
- for custom types are found via ADL.
-
Notes: - - Overloads for other types supplied in other headers.
This is an extension to TR1
hash_range(val.begin(), val.end())
-- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename K, typename C, typename A> - std::size_t hash_value(std::set<K, C, A> const & val); -template<typename K, typename C, typename A> - std::size_t hash_value(std::multiset<K, C, A> const & val);
Returns:
-
- hash_range(val.begin(), val.end());
Throws:
-
-
- Only throws if hash_value(T)
throws.
-
Notes:
-
- This is an extension to TR1
- | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::operator>> —
--template<typename charT> - std::basic_istream< charT > & - operator>>(std::basic_istream< charT > & is, time_period & tp);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::last_value<void> — Evaluate an InputIterator sequence.
--class last_value<void> { -public: - // types - typedef unspecified result_type; - - // invocation - template<typename InputIterator> - result_type operator()(InputIterator, InputIterator) const; -};
last_value
invocationtemplate<typename InputIterator> - result_type operator()(InputIterator first, InputIterator last) const;-
Effects:
-
- Dereferences every iterator in the sequence [first, last)
.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::swap —
--template<typename T1, typename T2, ..., typename TN> - void swap(variant<T1, T2, ..., TN> & lhs, variant<T1, T2, ..., TN> & rhs);
Effects:
-
- Swaps lhs
with rhs
by application
- of variant::swap
.
Throws:
-
- May fail with any exception arising from
- variant::swap
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::operator<< — operator<< for gregorian::greg_month typically streaming: Jan, Feb, Mar...
--template<typename charT, typename traits> - std::basic_ostream< charT, traits > & - operator<<(std::basic_ostream< charT, traits > & os, const greg_month & m);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::operator== — Compare tribools for equality.
--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 );
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 | -
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::time_duration — Base time duration type.
--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 -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::operator<< — operator<< for gregorian::greg_weekday typically streaming: Sun, Mon, Tue, ...
--template<typename charT, typename traits> - std::basic_ostream< charT, traits > & - operator<<(std::basic_ostream< charT, traits > & os, - const greg_weekday & wd);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator+= —
--local_date_time -operator+=(local_date_time & t, const boost::gregorian::years & y);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::operator+ —
--local_date_time -operator+(const local_date_time & t, const boost::gregorian::years & y);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ymd_order_spec — Enum for distinguishing the order of Month, Day, & Year.
-
-
-enum ymd_order_spec { ymd_order_iso, ymd_order_dmy, ymd_order_us };
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::hash_value —
--template<typename A, typename B> - std::size_t hash_value(std::pair<A, B> const & val);
Effects: - -
-size_t seed = 0; -hash_combine(seed, val.first); -hash_combine(seed, val.second); -return seed; -
hash_value(A)
- or hash_value(B)
throws.
- - | Copyright © 2005 Daniel James | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::identity_formatter — Identity formatter.
--template<typename RangeT> unspecified identity_formatter();
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::iends_with — 'Ends with' predicate ( case insensitive )
--template<typename Range1T, typename Range2T> - bool iends_with(const Range1T & Input, const Range2T & Test, - const std::locale & Loc = std::locale());
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
-An input sequence
A locale used for case insensitive comparison
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::iequals — 'Equals' predicate ( casa insensitive )
--template<typename Range1T, typename Range2T> - bool iequals(const Range1T & Input, const Range2T & Test, - const std::locale & Loc = std::locale());
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
-An input sequence
A locale used for case insensitive comparison
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_all — Erase all algorithm ( case insensitive ).
--template<typename SequenceT, typename RangeT> - void ierase_all(SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_all_copy — Erase all algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_all_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename RangeT> - SequenceT ierase_all_copy(const SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
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
-An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_first — Erase first algorithm ( case insensitive ).
--template<typename SequenceT, typename RangeT> - void ierase_first(SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_first_copy — Erase first algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_first_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename RangeT> - SequenceT ierase_first_copy(const SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
Remove the first occurrence 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
-An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_last — Erase last algorithm ( case insensitive ).
--template<typename SequenceT, typename RangeT> - void ierase_last(SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_last_copy — Erase last algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_last_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename RangeT> - SequenceT ierase_last_copy(const SequenceT & Input, const RangeT & Search, - const std::locale & Loc = std::locale());
Remove the last occurrence 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
-An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_nth — Erase nth algorithm.
--template<typename SequenceT, typename RangeT> - void ierase_nth(SequenceT & Input, const RangeT & Search, unsigned int Nth, - const std::locale & Loc = std::locale());
Remove the Nth occurrence of the substring in the input. The input sequence is modified in-place. Searching is case insensitive.
- -Parameters
-An input string
A locale used for case insensitive comparison
An index of the match to be replaced. The index is 0-based.
A substring to be searched for.
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ierase_nth_copy — Erase nth algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_nth_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, unsigned int Nth, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename RangeT> - SequenceT ierase_nth_copy(const SequenceT & Input, const RangeT & Search, - unsigned int Nth, - const std::locale & Loc = std::locale());
Remove the Nth occurrence 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
-An input string
A locale used for case insensitive comparison
An index of the match to be replaced. The index is 0-based.
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ifind_all — Find all algorithm ( case insensitive ).
--template<typename SequenceSequenceT, typename Range1T, typename Range2T> - SequenceSequenceT & - ifind_all(SequenceSequenceT & Result, Range1T & Input, - const Range2T & Search, const std::locale & Loc = std::locale());
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
-A container which will be searched.
A locale used for case insensitive comparison
A container that can hold copies of references to the substrings
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ifind_first — Find first algorithm ( case insensitive ).
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_first(Range1T & Input, const Range2T & Search, - const std::locale & Loc = std::locale());
Search for the first occurence of the substring in the input. Searching is case insensitive.
- -Parameters
-A string which will be searched.
A locale used for case insensitive comparison
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ifind_last — Find last algorithm ( case insensitive ).
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_last(Range1T & Input, const Range2T & Search, - const std::locale & Loc = std::locale());
Search for the last match a string in the input. Searching is case insensitive.
- -Parameters
-A string which will be searched.
A locale used for case insensitive comparison
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ifind_nth — Find n-th algorithm ( case insensitive ).
--template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_nth(Range1T & Input, const Range2T & Search, unsigned int Nth, - const std::locale & Loc = std::locale());
Search for the n-th (zero-indexed) occurence of the substring in the input. Searching is case insensitive.
- -Parameters
-A string which will be searched.
A locale used for case insensitive comparison
An index (zero-indexed) of the match to be found.
A substring to be searched for.
Returns:
-
- An iterator_range
delimiting the match. Returned iterator is either Range1T::iterator
or Range1T::const_iterator
, depending on the constness of the input parameter.
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::indeterminate — Keyword and test function for the indeterminate tribool value.
--bool indeterminate(tribool x, unspecified dummy = unspecified);
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.
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::logic::indeterminate_name — A locale facet specifying the name of the indeterminate value of a tribool.
-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; -};
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::int_adapter — Adapter to create integer types with +-infinity, and not a value.
-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; -};
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
public member functionsbool 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 & rhs) const;
bool operator==(const int & rhs) const;
bool operator!=(const int_adapter & rhs) const;
bool operator!=(const int & rhs) const;
bool operator<(const int_adapter & rhs) const;
bool operator<(const int & rhs) const;
bool operator>(const int_adapter & rhs) const;
int_type as_number() const;
special_values as_special() const;
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
-int_adapter operator+(const int_type rhs) const;
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
-int_adapter operator-(const int_type rhs) const;
int_adapter operator *(const int_adapter & rhs) const;
int_adapter operator *(const int rhs) const;-
Provided for cases when automatic conversion from 'int' to 'int_adapter' causes incorrect results.
-int_adapter operator/(const int_adapter & rhs) const;
int_adapter operator/(const int rhs) const;-
Provided for cases when automatic conversion from 'int' to 'int_adapter' causes incorrect results.
-int_adapter operator%(const int_adapter & rhs) const;
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 functionsbool 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 sv) ;
bool is_inf(int_type v) ;
bool is_neg_inf(int_type v) ;
bool is_pos_inf(int_type v) ;
bool is_not_a_number(int_type v) ;
special_values to_special(int_type v) ;
int_type maxcount() ;
int_adapter
private member functionsint compare(const int_adapter & rhs) const;
int_adapter mult_div_specials(const int_adapter & rhs) const;
int_adapter mult_div_specials(const int & rhs) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_all — Replace all algorithm ( case insensitive ).
--template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_all(SequenceT & Input, const Range1T & Search, - const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
A substring to be searched for
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_all_copy — Replace all algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_all_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_all_copy(const SequenceT & Input, const Range1T & Search, - const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_first — Replace first algorithm ( case insensitive ).
--template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_first(SequenceT & Input, const Range1T & Search, - const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
A substring to be searched for
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_first_copy — Replace first algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_first_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename Range2T, typename Range1T> - SequenceT ireplace_first_copy(const SequenceT & Input, - const Range2T & Search, - const Range1T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_last — Replace last algorithm ( case insensitive ).
--template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_last(SequenceT & Input, const Range1T & Search, - const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
A substring to be searched for
Returns: - - A reference to the modified input
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_last_copy — Replace last algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_last_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_last_copy(const SequenceT & Input, - const Range1T & Search, - const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_nth — Replace nth algorithm ( case insensitive ).
--template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_nth(SequenceT & Input, const Range1T & Search, - unsigned int Nth, const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
An index of the match to be replaced. The index is 0-based.
A substring to be searched for
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::ireplace_nth_copy — Replace nth algorithm ( case insensitive ).
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_nth_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, unsigned int Nth, - const Range3T & Format, - const std::locale & Loc = std::locale()); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_nth_copy(const SequenceT & Input, const Range1T & Search, - unsigned int Nth, const Range2T & Format, - const std::locale & Loc = std::locale());
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
-A substitute string
An input string
A locale used for case insensitive comparison
An index of the match to be replaced. The index is 0-based.
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_alnum — is_alnum predicate
--unspecified is_alnum(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_alpha — is_alpha predicate
--unspecified is_alpha(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_any_of — is_any_of predicate
--template<typename RangeT> unspecified is_any_of(const RangeT & Set);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_classified — is_classified predicate
--unspecified is_classified(std::ctype_base::mask Type, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_cntrl — is_cntrl predicate
--unspecified is_cntrl(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_digit — is_digit predicate
--unspecified is_digit(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_equal — is_equal functor
--struct is_equal { - - // public member functions - template<typename T1, typename T2> - bool operator()(const T1 &, const T2 &) const; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_from_range — is_from_range predicate
--template<typename CharT> unspecified is_from_range(CharT From, CharT To);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_graph — is_graph predicate
--unspecified is_graph(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_iequal — case insensitive version of is_equal
--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; -};
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_lower — is_lower predicate
--unspecified is_lower(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_print — is_print predicate
--unspecified is_print(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_punct — is_punct predicate
--unspecified is_punct(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::is_recursive_wrapper —
Determines whether the specified type is a specialization of
- recursive_wrapper
.
template<typename T> -class is_recursive_wrapper { -public: - // types - typedef unspecified type; - - // static constants - static const bool value = unspecified; -};
Value is true iff T
is a specialization of
- recursive_wrapper
.
Note:
- is_recursive_wrapper
is a model of
- MPL's
- IntegralConstant concept.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::is_reference_wrapper — Determine if a type T
is an instantiation of reference_wrapper
.
template<typename T> -class is_reference_wrapper { -public: - // static constants - static const bool value = unspecified; -};
The value
static
- constant will be true
iff the
- type T
is a specialization of
- reference_wrapper
.
- | Copyright © 1999, 2000 Jaakko Järvi Copyright © 2001, 2002 Peter Dimov Copyright © 2002 David Abrahams |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_space — is_space predicate
--unspecified is_space(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_upper — is_upper predicate
--unspecified is_upper(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::is_xdigit — is_xdigit predicate
--unspecified is_xdigit(const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::iso_extended_format — Extended format uses seperators YYYY-MM-DD.
-template<typename charT> -class iso_extended_format - : : public boost::date_time::iso_format_base< charT > -{ -public: - - // public static functions - bool has_date_sep_chars() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::iso_format — Format description for iso normal YYYYMMDD.
-template<typename charT> -class iso_format : public boost::date_time::iso_format_base< charT > { -public: - - // public static functions - bool has_date_sep_chars() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::iso_format_base — Class to provide common iso formatting spec.
-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() ; -};
iso_format_base
public static functionsmonth_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 sep) ;
bool is_fractional_time_sep(charT sep) ;
bool is_timezone_sep(charT sep) ;
charT element_sep_char() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::istarts_with — 'Starts with' predicate ( case insensitive )
--template<typename Range1T, typename Range2T> - bool istarts_with(const Range1T & Input, const Range2T & Test, - const std::locale & Loc = std::locale());
This predicate holds when the test string is a prefix of the Input. In other words, if the input starts with the test. Elements are compared case insensitively.
- -Parameters
-An input sequence
A locale used for case insensitive comparison
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 1999-2004 Jaakko Järvi, Gary 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)
Table of Contents
- -
-
- 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. -
-[STL94] 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/.
-[Jär99] C++ Function Object Binders Made Easy. . Lecture Notes in Computer Science. Springer. 2000.
-[Jär00] The Lambda Library : Lambda Abstraction in C++. Turku Centre for Computer Science. Technical Report . 378. 2000. www.tucs.fi/publications.
-[Jär01] The Lambda Library : Lambda Abstraction in C++. Second Workshop on C++ Template Programming. Tampa Bay, OOPSLA'01. . 2001. www.oonumerics.org/tmpw01/.
-[Jär03] The Lambda Library : unnamed functions in C++. . Software - Practice and Expreience. 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++. www.cc.gatech.edu/~yannis/fc++/. 2002.
-Last revised: November 28, 2004 at 03:29:16 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-
-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 6.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_
and
-n
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 6.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> |
-
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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.
-
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-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. - - -
-
-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 --
-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. -
-
-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).
-
-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 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 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.
-
-The function call operators have the effect of evaluating the lambda -functor. -Calls with too few arguments lead to a compile time error. -
-
-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 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. -
-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 --
-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 --
-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, 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 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.
-
-
-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:
-
-If the function object defines several function call operators, there is no way to specify different result types for them. -
-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++].
-
-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”).
-
-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<
and
-T
>(bind(arg-list
))bind<
have the exact same functionality —
-apart from the fact that for some nullary lambda functors the former does not work while the latter does.
-T
>(arg-list
)
-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.
-
-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); --
-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
.
-
-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. - -
- -
-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
argument must be a lambda expression that creates a lambda functor with an integral return type.
-The different cases are created with the condition
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") - ) -); --
-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<
-or to
-type
>catch_all
, which is the lambda expression equivalent to
-catch(...)
.
-
-
-
-The Example 6.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 6.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()) - ) - ) -); --
-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<
-can take arguments as well.
-
-They are passed directly to the constructor invocation and thus allow
-calls to constructors which take arguments.
-
-T
>()
-
-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 6.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 6.1. Construction and destruction related function objects.
-Function object call | -Wrapped expression | -
---|---|
constructor<T>()( |
-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>()( |
-new T( |
-
new_array<T>()(sz) |
-new T[sz] |
-
delete_ptr()(p) |
-delete p |
-
delete_array()(p) |
-delete p[] |
-
-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); --
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); - ... -} --
-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”).
-
-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 (!) --
-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. -
-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. - -
-
-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.
-
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. -
-
-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))); --
-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.
-
-
-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))); --
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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. - -
- 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)
.
-
-
-
-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. -
-- 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. -
-- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 6.3, “Test 1”.
-
-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 6.4, “Test 2”.
-
-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 6.4, “Test 2” 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 6.3. Test 1
-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 6.4. Test 2
-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]. -
-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. -
-The BLL works with the following compilers, that is, the compilers are capable of compiling the test cases that are included with the BLL: - -
-exception_test.cpp
results in an internal compiler error.
-)
-
- 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.
-
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 --
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. -
--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. -
-- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-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. - - -
-
- 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]
- 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”
-
- 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);-
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”. - - -
-- -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. - -
[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.
-
- | Copyright © 1999-2004 Jaakko Järvi, Gary Powell | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::last_finder — "Last" finder
--template<typename ContainerT> - unspecified last_finder(const ContainerT & Search); -template<typename ContainerT, typename PredicateT> - unspecified last_finder(const ContainerT & Search, PredicateT Comp);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::last_kday_of_month — Calculate something like Last Sunday of January.
-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; - virtual std::string to_string() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::last_last_rule_spec —
--struct last_last_rule_spec { - // types - typedef gregorian::date date_type; - typedef gregorian::last_kday_of_month start_rule; - typedef gregorian::last_kday_of_month end_rule; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::last_value — Evaluate an InputIterator sequence and return the - last value in the sequence.
-template<typename T> -class last_value { -public: - // types - typedef T result_type; - - // invocation - template<typename InputIterator> - result_type operator()(InputIterator, InputIterator) const; -};
last_value
invocationtemplate<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
.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-- Documentation for some libraries is available in alternative formats: -
- -std::bitset
, from Jeremy Siek and Chuck Allison.checked_delete
, checked_array_delete
, next
, prior
function templates, plus base-from-member idiom, from Dave Abrahams and others .- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
std::bitset
, from Jeremy Siek and Chuck Allison.checked_delete
, checked_array_delete
, next
, prior
function templates, plus base-from-member idiom, from Dave Abrahams and others .checked_delete
, checked_array_delete
, next
, prior
function templates, plus base-from-member idiom, from Dave Abrahams and others .- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::local_adjustor — Template that simplifies the creation of local time calculator.
-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) ; -};
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; -- -
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::local_date_time_base — Representation of "wall-clock" time in a particular time zone.
-template<typename utc_time_ = posix_time::ptime, - typename tz_type = date_time::time_zone_base<utc_time_> > -class local_date_time_base { -public: - // types - typedef utc_time_ utc_time_type; - typedef utc_time_type::time_duration_type time_duration_type; - typedef utc_time_type::date_type date_type; - typedef date_type::duration_type date_duration_type; - typedef utc_time_type::time_system_type time_system_type; - - // construct/copy/destruct - local_date_time_base(utc_time_type, boost::shared_ptr< tz_type >); - local_date_time_base(date_type, time_duration_type, - boost::shared_ptr< tz_type >, bool); - local_date_time_base(date_type, time_duration_type, - boost::shared_ptr< tz_type >, DST_CALC_OPTIONS); - local_date_time_base(const local_date_time_base &); - local_date_time_base(const boost::date_time::special_values, - boost::shared_ptr< tz_type > = boost::shared_ptr< tz_type >()); - ~local_date_time_base(); - - // public member functions - boost::shared_ptr< tz_type > zone() const; - bool is_dst() const; - utc_time_type utc_time() const; - utc_time_type local_time() const; - std::string to_string() const; - local_date_time_base - local_time_in(boost::shared_ptr< tz_type >, - time_duration_type = time_duration_type(0, 0, 0)) const; - std::string zone_name(bool = false) const; - std::string zone_abbrev(bool = false) const; - std::string zone_as_posix_string() const; - bool operator==(const local_date_time_base &) const; - bool operator!=(const local_date_time_base &) const; - bool operator<(const local_date_time_base &) const; - bool operator<=(const local_date_time_base &) const; - bool operator>(const local_date_time_base &) const; - bool operator>=(const local_date_time_base &) const; - local_date_time_base operator+(const date_duration_type &) const; - local_date_time_base operator+=(const date_duration_type &) ; - local_date_time_base operator-(const date_duration_type &) const; - local_date_time_base operator-=(const date_duration_type &) ; - local_date_time_base operator+(const time_duration_type &) const; - local_date_time_base operator+=(const time_duration_type &) ; - local_date_time_base operator-(const time_duration_type &) const; - local_date_time_base operator-=(const time_duration_type &) ; - time_duration_type operator-(const local_date_time_base &) const; - - // public static functions - time_is_dst_result - check_dst(date_type, time_duration_type, boost::shared_ptr< tz_type >) ; - - // private member functions - utc_time_type - construction_adjustment(utc_time_type, boost::shared_ptr< tz_type >, bool) ; - std::string zone_as_offset(const time_duration_type &, const std::string &) const; -};
Representation of "wall-clock" time in a particular time zone Local_date_time_base holds a time value (date and time offset from 00:00) along with a time zone. The time value is stored as UTC and conversions to wall clock time are made as needed. This approach allows for operations between wall-clock times in different time zones, and daylight savings time considerations, to be made. Time zones are required to be in the form of a boost::shared_ptr<time_zone_base>.
-local_date_time_base
construct/copy/destructlocal_date_time_base(utc_time_type t, boost::shared_ptr< tz_type > tz);-
This constructor interprets the passed time as a UTC time. So, for example, if the passed timezone is UTC-5 then the time will be adjusted back 5 hours. The time zone allows for automatic calculation of whether the particular time is adjusted for daylight savings, etc. If the time zone shared pointer is null then time stays unadjusted. -
-Parameters
-A UTC time
Timezone for to adjust the UTC time to.
local_date_time_base(date_type d, time_duration_type td, - boost::shared_ptr< tz_type > tz, bool dst_flag);-
This constructs a local time -- the passed time information understood to be in the passed tz. The DST flag must be passed to indicate whether the time is in daylight savings or not. -
-Throws: - - -- time_label_invalid if the time passed does not exist in the given locale. The non-existent case occurs typically during the shift-back from daylight savings time. When the clock is shifted forward a range of times (2 am to 3 am in the US) is skipped and hence is invalid. dst_not_valid if the DST flag is passed for a period where DST is not active.
-local_date_time_base(date_type d, time_duration_type td, - boost::shared_ptr< tz_type > tz, - DST_CALC_OPTIONS calc_option);-
This constructs a local time -- the passed time information understood to be in the passed tz. The DST flag is calculated according to the specified rule.
-local_date_time_base(const local_date_time_base & rhs);
local_date_time_base(const boost::date_time::special_values sv, - boost::shared_ptr< tz_type > tz = boost::shared_ptr< tz_type >());
~local_date_time_base();
local_date_time_base
public member functionsboost::shared_ptr< tz_type > zone() const;
bool is_dst() const;
utc_time_type utc_time() const;
utc_time_type local_time() const;
std::string to_string() const;-
Returns string in the form "2003-Aug-20 05:00:00 EDT". If time_zone is NULL the time zone abbreviation will be "UTC". The time zone abbrev will not be included if calling object is a special_value
-local_date_time_base -local_time_in(boost::shared_ptr< tz_type > new_tz, - time_duration_type td = time_duration_type(0, 0, 0)) const;-
returns a local_date_time_base in the given time zone with the optional time_duration added.
-std::string zone_name(bool as_offset = false) const;-
Optional bool parameter will return time zone as an offset (ie "+07:00" extended iso format). Empty string is returned for classes that do not use a time_zone
-std::string zone_abbrev(bool as_offset = false) const;-
Optional bool parameter will return time zone as an offset (ie "+0700" iso format). Empty string is returned for classes that do not use a time_zone
-std::string zone_as_posix_string() const;
bool operator==(const local_date_time_base & rhs) const;
bool operator!=(const local_date_time_base & rhs) const;
bool operator<(const local_date_time_base & rhs) const;
bool operator<=(const local_date_time_base & rhs) const;
bool operator>(const local_date_time_base & rhs) const;
bool operator>=(const local_date_time_base & rhs) const;
local_date_time_base operator+(const date_duration_type & dd) const;
local_date_time_base operator+=(const date_duration_type & dd) ;
local_date_time_base operator-(const date_duration_type & dd) const;
local_date_time_base operator-=(const date_duration_type & dd) ;
local_date_time_base operator+(const time_duration_type & td) const;
local_date_time_base operator+=(const time_duration_type & td) ;
local_date_time_base operator-(const time_duration_type & td) const;
local_date_time_base operator-=(const time_duration_type & td) ;
time_duration_type operator-(const local_date_time_base & rhs) const;
local_date_time_base
public static functionstime_is_dst_result -check_dst(date_type d, time_duration_type td, boost::shared_ptr< tz_type > tz) ;-
Determines if given time label is in daylight savings for given zone. Takes a date and time_duration representing a local time, along with time zone, and returns a time_is_dst_result object as result.
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::lock_error —
The lock_error class defines an exception type thrown - to indicate a locking related error has been detected.
--class lock_error : public std::logical_error { -public: - // construct/copy/destruct - lock_error(); -};
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::make_find_iterator — find iterator construction helper
--template<typename RangeT, typename FinderT> - find_iterator< typename range_result_iterator< RangeT >::type > - make_find_iterator(RangeT & Collection, FinderT Finder);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::make_recursive_variant — Simplifies declaration of recursive variant
types.
template<typename T1, typename T2 = unspecified, ..., - typename TN = unspecified> -class make_recursive_variant { -public: - // types - typedef boost::variant< unspecified > type; -};
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
):
-
-
Ti
is
- boost::recursive_variant_
then:
- variant< U1, U2, ..., UN >
;Ti
is of the
- form X *
then:
- substitute(X) *
;Ti
is of the
- form X &
then:
- substitute(X) &
;Ti
is of the
- form R (*)( X1, X2, ..., XN )
then:
- substitute(R) (*)( substitute(X1), substitute(X2), ..., substitute(XN) )
;Ti
is of the
- form F < X1, X2, ..., XN >
then:
- F< substitute(X1), substitute(X2), ..., substitute(XN) >
;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
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::make_split_iterator — split iterator construction helper
--template<typename RangeT, typename FinderT> - split_iterator< typename range_result_iterator< RangeT >::type > - make_split_iterator(RangeT & Collection, FinderT Finder);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::make_variant_over —
Exposes a variant
whose bounded types are the
- elements of the given type sequence.
template<typename Sequence> -class make_variant_over { -public: - // types - typedef variant< unspecified > type; -};
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.make_variant_over
may not be supported on your
- compiler. See
- BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT
- for more information.- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::microsec_clock — A clock providing microsecond level resolution.
-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 - template<typename time_zone_type> - time_type local_time(shared_ptr< time_zone_type >) ; - time_type local_time() ; - time_type universal_time() ; - - // private static functions - time_type create_time(TZ_FOR_CREATE) ; - time_type local_time() ; - time_type universal_time() ; - time_type create_time(FILETIME &, TZ_FOR_CREATE) ; -};
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.
- - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::minutes — Allows expression of durations as a minute count.
--class minutes : public boost::posix_time::time_duration { -public: - // construct/copy/destruct - minutes(long); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::month_formatter — Formats a month as as string into an ostream.
-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 &) ; -};
month_formatter
public static functionsstd::basic_ostream< charT > & -format_month(const month_type & month, std::basic_ostream< charT > & os) ;-
This function demands that month_type provide functions for converting to short and long strings if that capability is used.
-std::ostream & format_month(const month_type & month, std::ostream & os) ;-
This function demands that month_type provide functions for converting to short and long strings if that capability is used.
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::month_functor — Provides calculation to find next nth month given a date.
-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; -};
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.
- - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::months_duration — additional duration type that represents a logical month
-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 &) ; -};
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
public member functionsint_rep number_of_months() const;
duration_type get_neg_offset(const date_type & d) const;
duration_type get_offset(const date_type & d) const;
bool operator==(const months_type & rhs) const;
bool operator!=(const months_type & rhs) const;
months_type operator+(const months_type & rhs) const;
months_type & operator+=(const months_type & rhs) ;
months_type operator-(const months_type & rhs) const;
months_type & operator-=(const months_type & rhs) ;
months_type operator *(const int_type rhs) const;
months_type & operator *=(const int_type rhs) ;
months_type operator/(const int_type rhs) const;
months_type & operator/=(const int_type rhs) ;
months_type operator+(const years_type & y) const;
months_type & operator+=(const years_type & y) ;
months_type operator-(const years_type & y) const;
months_type & operator-=(const years_type & y) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-class mutex : private boost::noncopyable // Exposition only -{ -public: - // types - typedef implementation-defined scoped_lock; - - // construct/copy/destruct - mutex(); - ~mutex(); -};
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 , 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/destructmutex();-
Effects:
-
- Constructs a mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::next_weekday — Generates a date object representing the date of the following weekday from the given date.
--template<typename date_type, typename weekday_type> - date_type next_weekday(const date_type & d, const weekday_type & wd);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::notify —
--BOOST_PROGRAM_OPTIONS_DECL void notify(variables_map & m);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::nth_finder — "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);
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
-An index of the match to be find
A substring to be searched for.
Returns:
-
- An instance of the nth_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::nth_kday_of_month — Useful generator functor for finding holidays.
-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; - virtual std::string to_string() const; -};
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.
- - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::nth_kday_rule_spec —
--struct nth_kday_rule_spec { - // types - typedef gregorian::date date_type; - typedef gregorian::nth_kday_of_month start_rule; - typedef gregorian::nth_kday_of_month end_rule; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::nth_last_rule_spec —
--struct nth_last_rule_spec { - // types - typedef gregorian::date date_type; - typedef gregorian::nth_kday_of_month start_rule; - typedef gregorian::last_kday_of_month end_rule; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::null_dst_rules — Used for local time adjustments in places that don't use dst.
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 - bool match(const std::string &, bool) const; - const std::string & key(const std::string &) 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 & set_name(const char *) ; -};
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/destructoption_description();
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.
option_description(const char * name, const value_semantic * s, - const char * description);-
Initializes the class with the passed data.
-~option_description();
option_description
public member functionsbool match(const std::string & option, bool approx) const;-
Given 'option', specified in the input source, return 'true' is 'option' specifies *this.
-const std::string & key(const std::string & option) const;-
Return the key that should identify the option, in particular in the variables_map class. The 'option' parameter is the option spelling from the input source. If option name contains '*', returns 'option'. If long name was specified, it's the long name, otherwise it's a short name with prepended '-'.
-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;-
Return the parameter name and properties, formatted suitably for usage message.
-option_description
private member functionsoption_description & set_name(const char * name) ;
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::options_description —
--class options_description { -public: - // construct/copy/destruct - options_description(unsigned = m_default_line_length); - options_description(const std::string &, unsigned = m_default_line_length); - - // public member functions - void add(shared_ptr< option_description >) ; - options_description & add(const options_description &) ; - options_description_easy_init add_options() ; - const option_description & find(const std::string &, bool) const; - const option_description * find_nothrow(const std::string &, bool) const; - const std::vector< shared_ptr< option_description > > & options() const; - void print(std::ostream &) const; - - static const unsigned m_default_line_length; -};
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/destructoptions_description(unsigned line_length = m_default_line_length);-
Creates the instance.
-options_description(const std::string & caption, - unsigned line_length = m_default_line_length);-
Creates the instance. The 'caption' parameter gives the name of this 'options_description' instance. Primarily useful for output.
-options_description
public member functionsvoid 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.
-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.
-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.
-const option_description & find(const std::string & name, bool approx) const;
const option_description * -find_nothrow(const std::string & name, bool approx) const;
const std::vector< shared_ptr< option_description > > & options() const;
void print(std::ostream & os) const;-
Output 'desc' to the specified stream, calling 'f' to output each option_description element.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_date_formatter — Convert a date to string using format policies.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_month_formatter — Formats a month as as string into an ostream.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_time_formatter — Put a time type into a stream using appropriate facets.
-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 &) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_weekday_formatter — Formats a weekday.
-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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ostream_ymd_formatter — Convert ymd to a standard string formatting policies.
-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 &) ; -};
ostream_ymd_formatter
public static functionsvoid ymd_put(ymd_type ymd, ostream_type & os, const facet_type & f) ;-
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
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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());
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 & );
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::parse_match_result —
-template<typename charT> -struct parse_match_result { - // types - typedef std::basic_string< charT > string_type; - - // construct/copy/destruct - parse_match_result(); - - // public member functions - string_type remaining() const; - charT last_char() const; - bool has_remaining() const; - - string_type cache; - unsigned short match_depth; - short current_match; - static const short PARSE_ERROR; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::partial_date — Generates a date by applying the year to the given month and day.
-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; - virtual std::string to_string() const; -};
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/destructpartial_date(day_type d, month_type m);
partial_date(duration_rep days);-
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 functionsdate_type get_date(year_type y) const;-
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 --
date_type operator()(year_type y) const;
bool operator==(const partial_date & rhs) const;
bool operator<(const partial_date & rhs) const;
month_type month() const;
day_type day() const;
virtual std::string to_string() const;-
Returns string formatted with up to 3 digits: Jan-01 == "0" Feb-29 == "58" Dec-31 == "365"
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::partial_date_rule_spec —
--struct partial_date_rule_spec { - // types - typedef gregorian::date date_type; - typedef gregorian::partial_date start_rule; - typedef gregorian::partial_date end_rule; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::period — Provides generalized period type useful in date-time systems.
-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; -};
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 begining point and a duration or the begining point and the end point( end is NOT part of the period but 1 unit past it. A period will be "invalid" if either end_point <= begin_point or the given duration is <= 0. Any valid period will return false for is_null().
-Zero length periods are also considered invalid. Zero length periods are periods where the begining and end points are the same, or, the given duration is zero. For a zero length period, the last point will be one unit less than the begining point.
-In the case that the begin and last are the same, the period has a length of one unit.
-The best way to handle periods is usually to provide a begining 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
public member functionspoint_rep begin() const;
point_rep end() const;
point_rep last() const;
duration_rep length() const;
bool is_null() const;
bool operator==(const period & rhs) const;
bool operator<(const period & rhs) const;
void shift(const duration_rep & d) ;
bool contains(const point_rep & point) const;
bool contains(const period & other) const;
bool intersects(const period & other) const;
bool is_adjacent(const period & other) const;
bool is_before(const point_rep & point) const;
bool is_after(const point_rep & point) const;
period intersection(const period & other) const;
period merge(const period & other) const;
period span(const period & other) const;-
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----------) - * --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::period_formatter — Not a facet, but a class used to specify and control period formats.
-template<typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > -class period_formatter { -public: - // types - typedef std::basic_string< CharT > string_type; - typedef CharT char_type; - typedef std::basic_string< char_type >::const_iterator const_itr_type; - typedef std::vector< std::basic_string< CharT > > collection_type; - - // construct/copy/destruct - period_formatter(range_display_options = AS_CLOSED_RANGE, - const char_type *const = default_period_separator, - const char_type *const = default_period_start_delimeter, - const char_type *const = default_period_open_range_end_delimeter, - const char_type *const = default_period_closed_range_end_delimeter); - - // public member functions - OutItrT put_period_separator(OutItrT &) const; - OutItrT put_period_start_delimeter(OutItrT &) const; - OutItrT put_period_end_delimeter(OutItrT &) const; - range_display_options range_option() const; - void range_option(range_display_options) const; - void delimiter_strings(const string_type &, const string_type &, - const string_type &, const string_type &) ; - template<typename period_type, typename facet_type> - OutItrT put_period(OutItrT, std::ios_base &, char_type, - const period_type &, const facet_type &) const; - - static const char_type default_period_separator; - static const char_type default_period_start_delimeter; - static const char_type default_period_open_range_end_delimeter; - static const char_type default_period_closed_range_end_delimeter; -};
Provides settings for the following:
-period_separator -- default '/'
period_open_start_delimeter -- default '['
period_open_range_end_delimeter -- default ')'
period_closed_range_end_delimeter -- default ']'
display_as_open_range, display_as_closed_range -- default closed_range
Thus the default formatting for a period is as follows:
-[period.start()/period.last()] - * --
So for a typical date_period this would be
-[2004-Jan-04/2004-Feb-01] - * --
where the date formatting is controlled by the date facet
-period_formatter
construct/copy/destructperiod_formatter(range_display_options range_option = AS_CLOSED_RANGE, - const char_type *const period_separator = default_period_separator, - const char_type *const period_start_delimeter = default_period_start_delimeter, - const char_type *const period_open_range_end_delimeter = default_period_open_range_end_delimeter, - const char_type *const period_closed_range_end_delimeter = default_period_closed_range_end_delimeter);
period_formatter
public member functionsOutItrT put_period_separator(OutItrT & oitr) const;
OutItrT put_period_start_delimeter(OutItrT & oitr) const;
OutItrT put_period_end_delimeter(OutItrT & oitr) const;
range_display_options range_option() const;
void range_option(range_display_options option) const;
void delimiter_strings(const string_type & separator, - const string_type & start_delim, - const string_type & open_end_delim, - const string_type & closed_end_delim) ;
template<typename period_type, typename facet_type> - OutItrT put_period(OutItrT next, std::ios_base & a_ios, char_type a_fill, - const period_type & p, const facet_type & facet) const;-
This generic code will output any period using a facet to to output the 'elements'. For example, in the case of a date_period the elements will be instances of a date which will be formatted according the to setup in the passed facet parameter.
-The steps for formatting a period are always the same:
-put the start delimiter
put start element
put the separator
put either last or end element depending on range settings
put end delimeter depending on range settings
Thus for a typical date period the result might look like this:
-[March 01, 2004/June 07, 2004] <-- closed range - [March 01, 2004/June 08, 2004) <-- open range - - * --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::period_parser — Not a facet, but a class used to specify and control period parsing.
-template<typename date_type, typename CharT> -class period_parser { -public: - // types - typedef std::basic_string< CharT > string_type; - typedef CharT char_type; - typedef std::istreambuf_iterator< CharT > stream_itr_type; - typedef string_parse_tree< CharT > parse_tree_type; - typedef parse_tree_type::parse_match_result_type match_results; - typedef std::vector< std::basic_string< CharT > > collection_type; - - // construct/copy/destruct - period_parser(period_range_option = AS_CLOSED_RANGE, - const char_type *const = default_period_separator, - const char_type *const = default_period_start_delimeter, - const char_type *const = default_period_open_range_end_delimeter, - const char_type *const = default_period_closed_range_end_delimeter); - period_parser(const period_parser< date_type, CharT > &); - - // public member functions - period_range_option range_option() const; - void range_option(period_range_option) ; - collection_type delimiter_strings() const; - void delimiter_strings(const string_type &, const string_type &, - const string_type &, const string_type &) ; - template<typename period_type, typename duration_type, typename facet_type> - period_type get_period(stream_itr_type &, stream_itr_type &, - std::ios_base &, const period_type &, - const duration_type &, const facet_type &) const; - - // private member functions - void consume_delim(stream_itr_type &, stream_itr_type &, - const string_type &) const; - - static const char_type default_period_separator; - static const char_type default_period_start_delimeter; - static const char_type default_period_open_range_end_delimeter; - static const char_type default_period_closed_range_end_delimeter; -};
Provides settings for the following:
-period_separator -- default '/'
period_open_start_delimeter -- default '['
period_open_range_end_delimeter -- default ')'
period_closed_range_end_delimeter -- default ']'
display_as_open_range, display_as_closed_range -- default closed_range
For a typical date_period, the contents of the input stream would be
-[2004-Jan-04/2004-Feb-01] - * --
where the date format is controlled by the date facet
-period_parser
construct/copy/destructperiod_parser(period_range_option range_option = AS_CLOSED_RANGE, - const char_type *const period_separator = default_period_separator, - const char_type *const period_start_delimeter = default_period_start_delimeter, - const char_type *const period_open_range_end_delimeter = default_period_open_range_end_delimeter, - const char_type *const period_closed_range_end_delimeter = default_period_closed_range_end_delimeter);
period_parser(const period_parser< date_type, CharT > & p_parser);
period_parser
public member functionsperiod_range_option range_option() const;
void range_option(period_range_option option) ;
collection_type delimiter_strings() const;
void delimiter_strings(const string_type & separator, - const string_type & start_delim, - const string_type & open_end_delim, - const string_type & closed_end_delim) ;
template<typename period_type, typename duration_type, typename facet_type> - period_type get_period(stream_itr_type & sitr, stream_itr_type & stream_end, - std::ios_base & a_ios, const period_type & p, - const duration_type & dur_unit, - const facet_type & facet) const;-
This generic code will parse any period using a facet to to get the 'elements'. For example, in the case of a date_period the elements will be instances of a date which will be parsed according the to setup in the passed facet parameter.
-The steps for parsing a period are always the same:
-consume the start delimiter
get start element
consume the separator
get either last or end element depending on range settings
consume the end delimeter depending on range settings
Thus for a typical date period the contents of the input stream might look like this:
-[March 01, 2004/June 07, 2004] <-- closed range - [March 01, 2004/June 08, 2004) <-- open range - - * --
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::posix_time_zone — A time zone class constructed from a POSIX time zone string.
--class posix_time_zone : public boost::local_time::time_zone { -public: - // types - typedef boost::posix_time::time_duration time_duration_type; - typedef boost::tokenizer< boost::char_separator< char > > tokenizer; - typedef time_zone base_type; - typedef base_type::string_type string_type; - typedef base_type::stringstream_type stringstream_type; - - // construct/copy/destruct - posix_time_zone(const std::string &); - ~posix_time_zone(); - - // public member functions - virtual std::string std_zone_abbrev() const; - virtual std::string dst_zone_abbrev() const; - virtual std::string std_zone_name() const; - virtual std::string dst_zone_name() const; - virtual bool has_dst() const; - virtual posix_time::ptime dst_local_start_time(gregorian::greg_year) const; - virtual posix_time::ptime dst_local_end_time(gregorian::greg_year) const; - virtual time_duration_type base_utc_offset() const; - virtual time_duration_type dst_offset() const; - virtual string_type to_posix_string() const; - - // private member functions - void calc_zone(const std::string &) ; - void calc_rules(const std::string &, const std::string &) ; - void M_func(const std::string &, const std::string &) ; - void julian_no_leap(const std::string &, const std::string &) ; - void julian_day(const std::string &, const std::string &) ; - - // private static functions - std::string td_as_string(const time_duration_type &) ; -};
A POSIX time zone string takes the form of:<br> "std offset dst [offset],start[/time],end[/time]" (w/no spaces) 'std' specifies the abbrev of the time zone. - 'offset' is the offset from UTC. - 'dst' specifies the abbrev of the time zone during daylight savings time. - The second offset is how many hours changed during DST. Default=1 - 'start' and'end' are the dates when DST goes into (and out of) effect. - 'offset' takes the form of: [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59} - 'time' and 'offset' take the same form. Time defaults=02:00:00 - 'start' and 'end' can be one of three forms:<br> Mm.w.d {month=1-12, week=1-5 (5 is always last), day=0-6} - Jn {n=1-365 Feb29 is never counted} - n {n=0-365 Feb29 is counted in leap years} - Example "PST-5PDT01:00:00,M4.1.0/02:00:00,M10.1.0/02:00:00" - Exceptions will be thrown under these conditions:<br> An invalid date spec (see date class) - A boost::local_time::bad_offset exception will be thrown for:<br> A DST start or end offset that is negative or more than 24 hours - A UTC zone that is greater than +12 or less than -12 hours - A boost::local_time::bad_adjustment exception will be thrown for:<br> A DST adjustment that is 24 hours or more (positive or negative) -
- -posix_time_zone
public member functionsvirtual std::string std_zone_abbrev() const;
virtual std::string dst_zone_abbrev() const;-
For those time zones that have no DST, an empty string is used
-virtual std::string std_zone_name() const;-
The full STD name is not extracted from the posix time zone string. Therefore, the STD abbreviation is used in it's place
-virtual std::string dst_zone_name() const;-
The full DST name is not extracted from the posix time zone string. Therefore, the STD abbreviation is used in it's place. For time zones that have no DST, an empty string is used
-virtual bool has_dst() const;
virtual posix_time::ptime dst_local_start_time(gregorian::greg_year y) const;
virtual posix_time::ptime dst_local_end_time(gregorian::greg_year y) const;
virtual time_duration_type base_utc_offset() const;
virtual time_duration_type dst_offset() const;
virtual string_type to_posix_string() const;
posix_time_zone
private member functionsvoid calc_zone(const std::string & obj) ;-
Extract time zone abbreviations for STD & DST as well as the offsets for the time the shift occurs and how much of a shift. At this time full time zone names are NOT extracted so the abbreviations are used in their place
-void calc_rules(const std::string & start, const std::string & end) ;
void M_func(const std::string & s, const std::string & e) ;
void julian_no_leap(const std::string & s, const std::string & e) ;
void julian_day(const std::string & s, const std::string & e) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::previous_weekday — Generates a date object representing the date of the previous weekday from the given date.
--template<typename date_type, typename weekday_type> - date_type previous_weekday(const date_type & d, const weekday_type & wd);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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)
-
Table of Contents
-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”. -
-Last revised: July 30, 2004 at 13:20:27 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
This section focuses on some of the design questions. -
-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 instance - with strings of the same type (i.e. the 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 instance will be in the - internal encoding. This might avoid a conversion if - 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 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 must work with both. The only way is - to pass an additional flag telling if strings use ascii or internal encoding. - The instance of can then convert into some - other encoding if needed. -
-For the storage component, the only affected function is . - For Unicode input, the function should convert the value to the - internal encoding. It should also inform the 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. -
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
This section describes how the library can be used in specific - situations.
-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. -
-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. -
-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_winmain
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.
-
Having a single instance of the 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 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 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. -
-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. -
-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
- 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: -
-Go the the "test" directory and build the "test_convert" binary.
Set some non-ascii locale in the environmemt. On Linux, one can - run, for example:
--$ export LC_CTYPE=ru_RU.KOI8-R --
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.
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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. -
-The options description component has three main classes: - , and . The - first two together describe a single option. The - class contains the option's name, description and a pointer to , - which, in turn, knows the type of the option's value and can parse the value, - apply the default value, and so on. The class is a - container for instances of . -
-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 . 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"-
The syntactic information is provided by the
- boost::program_options::options_description
class
- and some methods of the
- boost::program_options::value_semantic
class
- and includes:
-
- name of the option, used to identify the option inside the - program, -
- description of the option, which can be presented to the user, -
- the allowed number of source tokens that comprise options's - value, which is used during parsing. -
Consider the following example: -
--options_description desc; -desc.add_options() - ("help", "produce help message") - ("compression", value<string>(), "compression level") - ("verbose", value<string>()->implicit(), "verbosity level") - ("email", value<string>()->multitoken(), "email to send to") - ; --
- For the first parameter, we specify only the name and the - description. No value can be specified in the parsed source. - For the first option, the user must specify a value, using a single - token. For the third 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 --help --compression 10 --verbose --email beadle@mars beadle2@mars --
- Sometimes the description can get rather long, for example, when - several option's values need separate documentation. Below we - describe some simple formatting mechanisms you can use. -
-The description string has one or more paragraphs, separated by - the newline character ('\n'). When an option is output, the library - will compute the indentation for options's description. Each of the - paragraph is output as a separate line with that intentation. If - a paragraph does not fit on one line it is spanned over multiple - lines (which will have the same indentation). -
-You may specify additional indent for the first specified by - inserting spaces at the beginning of a paragraph. For example: -
--options.add_options() - ("help", " A long help msg a long help msg a long help msg a long help -msg a long help msg a long help msg a long help msg a long help msg ") - ; --
- will specify a four-space indent for the first line. The output will - look like: -
-- --help A long help msg a long - help msg a long help msg - a long help msg a long - help msg a long help msg - a long help msg a long - help msg - --
For the case where line is wrapped, you can want an additional - indent for wrapped text. This can be done by - inserting a tabulator character ('\t') at the desired position. For - example: -
--options.add_options() - ("well_formated", "As you can see this is a very well formatted -option description.\n" - "You can do this for example:\n\n" - "Values:\n" - " Value1: \tdoes this and that, bla bla bla bla -bla bla bla bla bla bla bla bla bla bla bla\n" - " Value2: \tdoes something else, bla bla bla bla -bla bla bla bla bla bla bla bla bla bla bla\n\n" - " This paragraph has a first line indent only, -bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla"); --
- will produce: -
-- --well_formated As you can see this is a - very well formatted - option description. - You can do this for - example: - - Values: - Value1: does this and - that, bla bla - bla bla bla bla - bla bla bla bla - bla bla bla bla - bla - Value2: does something - else, bla bla - bla bla bla bla - bla bla bla bla - bla bla bla bla - bla - - This paragraph has a - first line indent only, - bla bla bla bla bla bla - bla bla bla bla bla bla - bla bla bla --
- The tab character is removed before output. Only one tabulator per - paragraph is allowed, otherwisee an exception of type - program_options::error is thrown. Finally, the tabulator is ignored if - it's is not on the first line of the paragraph or is on the last - possible position of the first line. -
-The semantic information is completely provided by the
- boost::program_options::value_semantic
class. For
- example:
-
-options_description desc; -desc.add_options() - ("compression", value<int>()->default_value(10), "compression level") - ("email", value< vector<string> >() - ->composing()->notifier(&your_function), "email") - ; --
- 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.
-
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 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); --
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).add_optional("input-file", -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". -
-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
- 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 - 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. -
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.
-
Don't forget to call the notify
function after you've
- stored all parsed values.
Environment variables are string variables
- which are available to all programs via the getenv
function
- of C runtime library. The operating system allows to set initial values
- for a given user, and the values can be further changed on the command
- line. For example, on Windows one can use the
- autoexec.bat
file or (on recent versions) the
- Control Panel/System/Advanced/Environment Variables
- dialog, and on Unix —, the /etc/profile
,
- ~/profile
and ~/bash_profile
- files. Because environment variables can be set for the entire system,
- they are particularly suitable for options which apply to all programs.
-
The environment variables can be parsed with the - function. The function have several overloaded - versions. The first parameter is always an - instance, and the second specifies what variables must be processed, and - what option names must correspond to it. To describe the second - parameter we need to consider naming conventions for environment - variables.
-If you have an option that should be specified via environment
- variable, you need make up the variable's name. To avoid name clashes,
- we suggest that you use a sufficiently unique prefix for environment
- variables. Also, while option names are most likely in lower case,
- environment variables conventionally use upper case. So, for an option
- name proxy
the environment variable might be called
- BOOST_PROXY
. During parsing, we need to perform reverse
- conversion of the names. This is accomplished by passing the choosen
- prefix as the second parameter of the function.
- Say, if you pass BOOST_
as the prefix, and there are
- two variables, CVSROOT
and BOOST_PROXY
, the
- first variable will be ignored, and the second one will be converted to
- option proxy
.
-
The above logic is sufficient in many cases, but it is also
- possible to pass, as the second parameter of the
- function, any function taking a std::string
and returning
- std::string
. That function will be called for each
- environment variable and should return either the name of the option, or
- empty string if the variable should be ignored.
-
The following table describes all the important symbols in the - library, for quick access.
-Symbol | -Description | -
---|---|
Options description component | |
- | describes a number of options | -
- | defines the option's value | -
Parsers component | |
- | parses command line | -
- | parses config file | -
- | parses environment | -
Storage component | |
- | storage for option values | -
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
namespace boost { - namespace program_options { - namespace command_line_style { - enum style_t; - } - } -}-
namespace boost { - class environment_iterator; -}-
namespace boost { - template<typename Derived, typename ValueType> class eof_iterator; -}-
namespace boost { - namespace program_options { - class ambiguous_option; - class error; - class invalid_command_line_style; - class invalid_command_line_syntax; - class invalid_option_value; - class invalid_syntax; - class multiple_occurrences; - class multiple_values; - class too_few_positional_options_error; - class too_many_positional_options_error; - class unknown_option; - class validation_error; - } -}-
namespace boost { - namespace program_options { - template<typename charT> class basic_option; - - typedef basic_option< char > option; - typedef basic_option< wchar_t > woption; - } -}-
namespace boost { - namespace program_options { - class duplicate_option_error; - class option_description; - class options_description; - class options_description_easy_init; - } -}-
namespace boost { - namespace program_options { - template<typename charT> class basic_command_line_parser; - template<typename charT> class basic_parsed_options; - - template<> class basic_parsed_options<wchar_t>; - - 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 *); - } -}-
namespace boost { - namespace program_options { - class positional_options_description; - } -}-
namespace boost { - namespace program_options { - template<typename T, typename charT = char> class typed_value; - class untyped_value; - 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>; - 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 *); - } -}-
namespace boost { - namespace program_options { - class abstract_variables_map; - class variable_value; - 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 &); - } -}-
- -BOOST_PROGRAM_OPTIONS_VERSION-
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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;-
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
- 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. -
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 - class to parse the command - line, not the - 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. -
-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 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. -
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::ptime — Time type with no timezone or other adjustments.
--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 -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::range_finder — "Range" finder
--template<typename ForwardIteratorT> - unspecified range_finder(ForwardIteratorT Begin, ForwardIteratorT End); -template<typename ForwardIteratorT> - unspecified range_finder(iterator_range< ForwardIteratorT > Range);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::read_write_mutex —
The read_write_mutex class is a model of the - ReadWriteMutex concept.
--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(); -};
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 , 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. -
-read_write_mutex
construct/copy/destructread_write_mutex(boost::read_write_scheduling_policy count);-
Effects:
-
- Constructs a read_write_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::recursive_mutex —
The recursive_mutex class is a model of the - Mutex concept.
--class recursive_mutex : private boost::noncopyable // Exposition only -{ -public: - // types - typedef implementation-defined scoped_lock; - - // construct/copy/destruct - recursive_mutex(); - ~recursive_mutex(); -};
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 12.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 , 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/destructrecursive_mutex();-
Effects:
-
- Constructs a recursive_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::recursive_timed_mutex —
The recursive_timed_mutex class is a model of the - TimedMutex concept.
--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(); -};
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 12.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 , 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/destructrecursive_timed_mutex();-
Effects:
-
- Constructs a recursive_timed_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::recursive_try_mutex —
The recursive_try_mutex class is a model of the - TryMutex concept.
--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(); -};
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 12.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 , 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/destructrecursive_try_mutex();-
Effects:
-
- Constructs a recursive_try_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::recursive_wrapper — Solves circular dependencies, enabling recursive types.
-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; -};
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:
-recursive_wrapper
must be capable of construction via
- operator new
. Thus, for instance, references are not
- supported.recursive_wrapper
construct/copy/destructrecursive_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
.
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
.
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
.
~recursive_wrapper();-
Deletes the content of *this
.
Throws: - - Will not throw.
-recursive_wrapper
modifiersvoid swap(recursive_wrapper & other);-
Exchanges contents of *this
and
- other
.
Throws: - - Will not throw.
-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
.
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
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 1999, 2000 Jaakko Järvi
Copyright © 2001, 2002 Peter Dimov
Copyright © 2002 David Abrahams
Table of Contents
- -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.
Last revised: July 09, 2004 at 00:56:42 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
.
- | Copyright © 1999, 2000 Jaakko Järvi Copyright © 2001, 2002 Peter Dimov Copyright © 2002 David Abrahams |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -}-
- | Copyright © 1999, 2000 Jaakko Järvi Copyright © 2001, 2002 Peter Dimov Copyright © 2002 David Abrahams |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table of Contents
-Elements:
-boostbook
- Defines a BoostBook bookclass
- Declares a class or class templateclass-specialization
- A specialization (partial or full) of a class templatecode
- Mimics the code
tag in HTMLcompile-fail-test
- A testcase that should fail to compilecompile-test
- A testcase that should compile correctlycomplexity
- The time/space/etc. complexity of a functionconstructor
- Declares a constructor of the enclosing classcopy-assignment
- Declares a copy-assignment operatordata-member
- Declares a data member of a classdefault
- The default value of a function or template parameterdescription
- Detailed description of a constructdestructor
- Declares a destructor for the enclosing classeffects
- Declares the side effects of a functionenum
- Declares an enumeration typeenumvalue
- A single value of an enumerationfree-function-group
- A set of functions that are grouped together under one namefunction
- Declares a functionfunctionname
- References a function with the given nameheader
- Declares a C++ header with the given nameif-fails
- What it means when a testcase failsinherit
- Declares a base class of the enclosing class or structlib
- A library dependencylibrary
- Top-level element for a librarylibrary-reference
- Declares the reference material for a librarylibrarycategory
- Declares that the enclosing library is in this categorylibrarycategorydef
- Defines a new library categorylibrarycategorylist
- Categorized listing of librarieslibraryinfo
- Provides information about a librarylibrarylist
- Placeholder for an alphabetical list of librarieslibraryname
- References a library of the given namelibrarypurpose
- Describes in one short sentence or phrase the purpose of a librarylink-fail-test
- Declares a test that should compile but fail to linklink-test
- Declares a test that should compile and linkmethod
- Declares a method, i.e., a member functionmethod-group
- A set of methods that are grouped together under one namenamespace
- Declares a namespacenotes
- Non-normative notes about a function's semanticsoverloaded-function
- An overloaded functionoverloaded-method
- An overloaded methodparameter
- A function parameterparamtype
- The type of a function parameterpostconditions
- Conditions that must hold after the function returnsprecondition
- Conditions that must be met prior to executing a functionprogramlisting
- A sample of program codepurpose
- A short description of an entity's userationale
- Describes the rationale for a particular function's designrequirement
- A requirement/property in the Jamfile for a testcaserequires
- Declares the requirements of a functionreturns
- Description of the return value of a functionrun-fail-test
- A testcase that should compile and link, but fail on executionrun-test
- A testcase that should compile, link, and executesignature
- One signature of an overloaded function or methodsnippet
- Pulls in a code snippet from a programlisting
elementsource
- Defines source code for a testspecialization
- Defines the specialization arguments for a class specializationstatic-constant
- Declares a static constant, e.g., const int foo = 5;
.struct
- Declares a C++ structstruct-specialization
- A specialization (full or partial) of a struct templatetemplate
- Declares the template parameters of a class or functiontemplate-arg
- A template argument in a specializationtemplate-nontype-parameter
- A nontype template parametertemplate-type-parameter
- Declares a template type parametertemplate-varargs
- Declares a variable-length list of template parameterstestsuite
- Describes a library testsuitethrows
- Description of the exceptions thrown by a functiontype
- The type of an element or return type of a functiontypedef
- Declares a typedefunion
- Declares a C++ union or union templateunion-specialization
- A specialization (full or partial) of a union templateusing-class
- Injects the method and function names of a class into the local scopeusing-namespace
- Injects the declared names from a namespace into the local scope- | Copyright © 2003-2005 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::reference_wrapper —
- Contains a reference to an object of type
- T
.
-
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&);
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/destructexplicit reference_wrapper(T& t);-
Effects:
-
- Constructs a
- reference_wrapper
- object that stores a reference to
- t
.
Throws:
-
- Does not throw.
reference_wrapper
accessoperator T&() const;-
Returns:
-
- The stored reference.
Throws:
-
- Does not throw.
T& get() const;-
Returns:
-
- The stored reference.
Throws:
-
- Does not throw.
T* get_pointer() const;-
Returns:
-
- A pointer to the object referenced by the stored reference.
Throws:
-
- Does not throw.
reference_wrapper
constructorsreference_wrapper<T> ref(T& t);-
Returns:
-
- reference_wrapper<T>(t)
Throws:
-
- Does not throw.
reference_wrapper<T const> cref(T const& t);-
Returns:
-
- reference_wrapper<T const>(t)
Throws:
-
- Does not throw.
- | Copyright © 1999, 2000 Jaakko Järvi Copyright © 2001, 2002 Peter Dimov Copyright © 2002 David Abrahams |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_all — Replace all algorithm.
--template<typename SequenceT, typename Range1T, typename Range2T> - void replace_all(SequenceT & Input, const Range1T & Search, - const Range2T & Format);
Replace all occurrences of the search string in the input with the format string. The input sequence is modified in-place.
- -Parameters
-A substitute string
An input string
A substring to be searched for
Returns: - - A reference to the modified input
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_all_copy — Replace all algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_all_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_all_copy(const SequenceT & Input, const Range1T & Search, - const Range2T & Format);
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
-A substitute string
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_all_regex — Replace all regex algorithm.
--template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - void replace_all_regex(SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, - match_flag_type Flags = match_default|format_default);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_all_regex_copy — Replace all regex algorithm.
--template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT, typename FormatStringTraitsT, - typename FormatStringAllocatorT> - OutputIteratorT - replace_all_regex_copy(OutputIteratorT Output, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & 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 FormatStringTraitsT, typename FormatStringAllocatorT> - SequenceT replace_all_regex_copy(const SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, - match_flag_type Flags = match_default|format_default);
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
-Regex options
Regex format definition
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_first — Replace first algorithm.
--template<typename SequenceT, typename Range1T, typename Range2T> - void replace_first(SequenceT & Input, const Range1T & Search, - const Range2T & Format);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_first_copy — Replace first algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_first_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_first_copy(const SequenceT & Input, - const Range1T & Search, - const Range2T & Format);
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
-A substitute string
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_head — Replace head algorithm.
--template<typename SequenceT, typename RangeT> - void replace_head(SequenceT & Input, unsigned int N, const RangeT & Format);
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
-A substitute string
An input string
Length of the head
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_head_copy — Replace head algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - replace_head_copy(OutputIteratorT Output, const Range1T & Input, - unsigned int N, const Range2T & Format); -template<typename SequenceT, typename RangeT> - SequenceT replace_head_copy(const SequenceT & Input, unsigned int N, - const RangeT & Format);
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
-A substitute string
An input string
Length of the head
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_last — Replace last algorithm.
--template<typename SequenceT, typename Range1T, typename Range2T> - void replace_last(SequenceT & Input, const Range1T & Search, - const Range2T & Format);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_last_copy — Replace last algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_last_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, const Range3T & Format); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_last_copy(const SequenceT & Input, const Range1T & Search, - const Range2T & Format);
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
-A substitute string
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_nth — Replace nth algorithm.
--template<typename SequenceT, typename Range1T, typename Range2T> - void replace_nth(SequenceT & Input, const Range1T & Search, - unsigned int Nth, const Range2T & Format);
Replace an Nth (zero-indexed) match of the search string in the input with the format string. Input sequence is modified in-place.
- -Parameters
-A substitute string
An input string
An index of the match to be replaced. The index is 0-based.
A substring to be searched for
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_nth_copy — Replace nth algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_nth_copy(OutputIteratorT Output, const Range1T & Input, - const Range2T & Search, unsigned int Nth, - const Range3T & Format); -template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_nth_copy(const SequenceT & Input, const Range1T & Search, - unsigned int Nth, const Range2T & Format);
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
-A substitute string
An input string
An index of the match to be replaced. The index is 0-based.
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_range — Replace range algorithm.
--template<typename SequenceT, typename RangeT> - void replace_range(SequenceT & Input, - const iterator_range< typename range_iterator< SequenceT >::type > & SearchRange, - const RangeT & Format);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_range_copy — Replace range algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - replace_range_copy(OutputIteratorT Output, const Range1T & Input, - const iterator_range< typename range_const_iterator< Range1T >::type > & SearchRange, - const Range2T & Format); -template<typename SequenceT, typename RangeT> - SequenceT replace_range_copy(const SequenceT & Input, - const iterator_range< typename range_const_iterator< SequenceT >::type > & SearchRange, - const RangeT & Format);
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
-A substitute string
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_regex — Replace regex algorithm.
--template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - void replace_regex(SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, - match_flag_type Flags = match_default|format_default);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_regex_copy — Replace regex algorithm.
--template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT, typename FormatStringTraitsT, - typename FormatStringAllocatorT> - OutputIteratorT - replace_regex_copy(OutputIteratorT Output, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & 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 FormatStringTraitsT, typename FormatStringAllocatorT> - SequenceT replace_regex_copy(const SequenceT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > & Format, - match_flag_type Flags = match_default|format_default);
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
-Regex options
Regex format definition
An input string
An output iterator to which the result will be copied
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_tail — Replace tail algorithm.
--template<typename SequenceT, typename RangeT> - void replace_tail(SequenceT & Input, unsigned int N, const RangeT & Format);
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
-A substitute string
An input string
Length of the tail
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::replace_tail_copy — Replace tail algorithm.
--template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - replace_tail_copy(OutputIteratorT Output, const Range1T & Input, - unsigned int N, const Range2T & Format); -template<typename SequenceT, typename RangeT> - SequenceT replace_tail_copy(const SequenceT & Input, unsigned int N, - const RangeT & Format);
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
-A substitute string
An input string
Length of the tail
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::signals::scoped_connection — Limits a signal-slot connection lifetime to a particular scope.
--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; -};
scoped_connection
construct/copy/destructscoped_connection(const connection& other);-
Effects:
-
- this
references
- the connection referenced by
- other
.
Throws:
-
- Will not throw.
~scoped_connection();-
Effects:
-
- If
- this->connected()
,
- disconnects the signal-slot connection.
scoped_connection
connection managementvoid disconnect() const;-
Effects:
-
- If
- this->connected()
,
- disconnects the signal and slot referenced by this;
- otherwise, this operation is a no-op.
Postconditions:
-
- !this->connected()
.
bool connected() const;-
Returns:
-
- true
if this
- references a non-NULL connection that is still active
- (connected), and false
- otherwise.
Throws:
-
- Will not throw.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::second_clock — A clock providing time level services based on C time_t capabilities.
-template<typename time_type> -class second_clock { -public: - // types - typedef time_type::date_type date_type; - typedef time_type::time_duration_type time_duration_type; - - // public static functions - time_type local_time() ; - time_type universal_time() ; - template<typename time_zone_type> - time_type local_time(boost::shared_ptr< time_zone_type >) ; - - // private static functions - time_type create_time(::std::tm *) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::seconds — Allows expression of durations as a seconds count.
--class seconds : public boost::posix_time::time_duration { -public: - // construct/copy/destruct - seconds(long); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::signal — Safe multicast callback.
-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()); -};
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.
- -- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::signalN — Set of safe multicast callback types.
-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; -};
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/destructsignalN(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()
~signalN();-
Effects:
-
- Disconnects all slots connected to *this
.
signalN
connection managementsignals::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.
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.
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.
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.
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
invocationresult_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).
-- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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)
Table of Contents
-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.
-Last revised: May 04, 2004 at 18:17:22 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 }; - } -}-
namespace boost { - template<typename SlotFunction> class slot; -}-
namespace boost { - namespace signals { - class trackable; - } -}-
namespace boost { - namespace signals { - class connection; - void swap(connection&, connection&); - class scoped_connection; - } -}-
namespace boost { - template<typename Visitor, typename T> - void visit_each(const Visitor&, const T&, int); -}-
namespace boost { - template<typename T> class last_value; - - template<> class last_value<void>; -}-
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Last revised: March 12, 2003 at 23:27:23 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
"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).
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).
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 |
-
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
- |
-
Transform Iterator Adaptor |
-This transform iterator adaptor performs an
- |
-
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. |
-
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.
Last revised: March 12, 2003 at 23:27:22 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
- 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.
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).
- 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.
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.
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.
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.
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.
Last revised: July 20, 2004 at 17:03:55 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Test | -Type | -Description | -If failing... | -
---|---|---|---|
- | run |
-Ensure that calling |
-- |
- | run |
-Test deletion of slots. |
-- |
- | run |
-Test slot group ordering. |
-- |
- | run |
-Basic test of signal/slot connections and invocation using the
- |
-- |
- | run |
-Basic test of signal/slot connections and invocation using the
- |
-The |
-
- | run |
-Test automatic lifetime management using
- |
-- |
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-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 | -
---|---|
|
-
|
-
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 - |
--struct HelloWorld -{ - void operator()() const - { - std::cout << "Hello, World!" << std::endl; - } -}; - -// ... - -// Signal with no arguments and a void return value - |
-
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 | -
---|---|
|
-
|
-
By default, slots are called in first-in first-out (FIFO) order, -so the output of this program will be as expected:
--Hello, World! --
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, int
s, and are ordered by the integer
-< relation. Here's how we construct Hello, World:
Preferred syntax | -Portable syntax | -
---|---|
|
-
|
-
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! --
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 | -
---|---|
|
-
|
-
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.
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; } - - |
--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; } - - |
-
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 float
s). 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 | -
---|---|
|
-
|
-
Now we can connect slots that perform arithmetic functions and -use the signal:
--sig.-connect
("ient); -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 | -
---|---|
|
-
|
-
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; - } -}; --
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
Slots can be temporarily "blocked", meaning that they will be
-ignored when the signal is invoked but have not been disconnected. The
-block
member function
-temporarily blocks a slot, which can be unblocked via
-unblock
. Here is an example of
-blocking/unblocking slots:
-boost::signals::connection c = sig.-connect
(HelloWorld()); -sig(); // Prints "Hello, World!" - -c.block
(); // block the slot -assert(c.blocked
()); -sig(); // No output: the slot is blocked - -c.unblock
(); // unblock the slot -sig(); // Prints "Hello, World!"
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
-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); - |
-
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.
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.
-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. |
--class Button -{ - typedef |
-
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.
Signals can be used to implement flexible Document-View
- architectures. The document will contain a signal to which each of
- the views can connect. The following Document
class
- defines a simple text document that supports mulitple views. Note
- that it stores a single signal to which all of the views will be
- connected.
class Document -{ -public: - typedef boost::signal<void (bool)> signal_t; - typedef boost::signals::connection connection_t; - -public: - Document() - {} - - connection_t connect(signal_t::slot_function_type subscriber) - { - return m_sig.connect(subscriber); - } - - void disconnect(connection_t subscriber) - { - subscriber.disconnect(); - } - - void append(const char* s) - { - m_text += s; - m_sig(true); - } - - const std::string& getText() const - { - return m_text; - } - -private: - signal_t m_sig; - std::string m_text; -};-
Next, we can define a View
base class from which
- views can derive. This isn't strictly required, but it keeps the
- Document-View logic separate from the logic itself. Note that the
- constructor just connects the view to the document and the
- destructor disconnects the view.
-class View -{ -public: - View(Document& m) - : m_document(m) - { - m_connection = m_document.connect(boost::bind(&View::refresh, this, _1)); - } - - virtual ~View() - { - m_document.disconnect(m_connection); - } - - virtual void refresh(bool bExtended) const = 0; - -protected: - Document& m_document; - -private: - Document::connection_t m_connection; -}; --
Finally, we can begin to define views. The
- following TextView
class provides a simple view of the
- document text.
class TextView : public View -{ -public: - TextView(Document& doc) - : View(doc) - {} - - virtual void refresh(bool bExtended) const - { - std::cout << "TextView: " << m_document.getText() << std::endl; - } -};-
Alternatively, we can provide a view of the document
- translated into hex values using the HexView
- view:
class HexView : public View -{ -public: - HexView(Document& doc) - : View(doc) - {} - - virtual void refresh(bool bExtended) const - { - const std::string& s = m_document.getText(); - - std::cout << "HexView:"; - - for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) - std::cout << ' ' << std::hex << static_cast<int>(*it); - - std::cout << std::endl; - } -};-
To tie the example together, here is a
- simple main
function that sets up two views and then
- modifies the document:
int main(int argc, char* argv[]) -{ - Document doc; - TextView v1(doc); - HexView v2(doc); - - doc.append(argc == 2 ? argv[1] : "Hello world!"); - return 0; -}-
The complete example source, contributed by Keith MacDonald,
- is available in libs/signals/example/doc_view.cpp
.
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
.
Last revised: May 18, 2005 at 16:09:34 GMT |
-Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::CV::simple_exception_policy — Template to shortcut the constrained_value policy creation process.
-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) ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::simple_format — Class to provide simple basic formatting rules.
-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() ; -};
simple_format
public static functionsconst 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() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::posix_time::simple_time_rep — Simple implementation for the 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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::slot — Pass slots as function arguments.
-template<typename SlotFunction> -class slot { -public: - // construct/copy/destruct - template<typename Slot> slot(Slot); -};
slot
construct/copy/destructtemplate<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.
- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::gregorian::special_value_from_string — Return special_value from string argument.
--special_values special_value_from_string(const std::string & s);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::special_values_formatter — Class that provides generic formmatting ostream formatting for special values.
-template<typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > -class special_values_formatter { -public: - // types - typedef std::basic_string< CharT > string_type; - typedef CharT char_type; - typedef std::vector< string_type > collection_type; - - // construct/copy/destruct - special_values_formatter(); - special_values_formatter(const char_type *const *, const char_type *const *); - special_values_formatter(typename collection_type::iterator, - typename collection_type::iterator); - - // public member functions - OutItrT put_special(OutItrT, const boost::date_time::special_values &) const; - - static const char_type default_special_value_names; -};
This class provides for the formmating of special values to an output stream. In particular, it produces strings for the values of negative and positive infinity as well as not_a_date_time.
-While not a facet, this class is used by the date and time facets for formatting special value types.
-special_values_formatter
construct/copy/destructspecial_values_formatter();-
Default strings are not-a-date-time -infinity +infinity
-special_values_formatter(const char_type *const * begin, - const char_type *const * end);-
This constructor will take pair of iterators from an array of strings that represent the special values and copy them for use in formatting special values.
-const char* const special_value_names[]={"nadt","-inf","+inf" }; - - special_value_formatter svf(&special_value_names[0], &special_value_names[3]); - * --
special_values_formatter(typename collection_type::iterator beg, - typename collection_type::iterator end);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::special_values_parser — Class for special_value parsing.
-template<typename date_type, typename charT> -class special_values_parser { -public: - // types - typedef std::basic_string< charT > string_type; - typedef std::istreambuf_iterator< charT > stream_itr_type; - typedef date_type::duration_type duration_type; - typedef string_parse_tree< charT > parse_tree_type; - typedef parse_tree_type::parse_match_result_type match_results; - typedef std::vector< std::basic_string< charT > > collection_type; - typedef charT char_type; - - // construct/copy/destruct - special_values_parser(); - special_values_parser(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &); - special_values_parser(typename collection_type::iterator, - typename collection_type::iterator); - special_values_parser(const special_values_parser< date_type, charT > &); - - // public member functions - void sv_strings(const string_type &, const string_type &, - const string_type &, const string_type &, - const string_type &) ; - bool match(stream_itr_type &, stream_itr_type &, match_results &) const; - - static const char_type nadt_string; - static const char_type neg_inf_string; - static const char_type pos_inf_string; - static const char_type min_date_time_string; - static const char_type max_date_time_string; -};
TODO: add doc-comments for which elements can be changed Parses input stream for strings representing special_values. Special values parsed are:
-not_a_date_time
neg_infin
pod_infin
min_date_time
max_date_time
special_values_parser
construct/copy/destructspecial_values_parser();
special_values_parser(const string_type & nadt_str, - const string_type & neg_inf_str, - const string_type & pos_inf_str, - const string_type & min_dt_str, - const string_type & max_dt_str);
special_values_parser(typename collection_type::iterator beg, - typename collection_type::iterator end);
special_values_parser(const special_values_parser< date_type, charT > & svp);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::split_iterator — 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 RangeT> - split_iterator(RangeT &, FinderT); - - // public member functions - bool eof() const; - - // private member functions - const match_type & dereference() const; - void increment() ; - bool equal(const split_iterator &) const; -};
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/destructsplit_iterator();-
Construct null iterator. All null iterators are equal.
- -Postconditions: - - eof()==true
-split_iterator(const split_iterator & Other);-
Construct a copy of the split_iterator
-template<typename FinderT> - split_iterator(IteratorT Begin, IteratorT End, FinderT Finder);-
Construct new split_iterator for a given finder and a range.
-template<typename FinderT, typename RangeT> - split_iterator(RangeT & Col, FinderT Finder);-
Construct new split_iterator for a given finder and a collection.
-split_iterator
private member functionsconst match_type & dereference() const;
void increment() ;
bool equal(const split_iterator & Other) const;
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::split_regex — Split regex algorithm.
--template<typename SequenceSequenceT, typename RangeT, typename CharT, - typename RegexTraitsT> - SequenceSequenceT & - split_regex(SequenceSequenceT & Result, const RangeT & Input, - const basic_regex< CharT, RegexTraitsT > & Rx, - match_flag_type Flags = match_default);
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
-Regex options
A container which will be searched.
A container that can hold copies of references to the substrings.
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
-- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::split_timedate_system — An unadjusted time system implementation.
-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(special_values) ; - 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) ; -};
split_timedate_system
public static functionstime_rep_type get_time_rep(special_values sv) ;
time_rep_type -get_time_rep(const date_type & day, const time_duration_type & tod, - date_time::dst_flags dst = not_dst) ;
date_type get_date(const time_rep_type & val) ;
time_duration_type get_time_of_day(const time_rep_type & val) ;
std::string zone_name(const time_rep_type & ) ;
bool is_equal(const time_rep_type & lhs, const time_rep_type & rhs) ;
bool is_less(const time_rep_type & lhs, const time_rep_type & rhs) ;
time_rep_type -add_days(const time_rep_type & base, const date_duration_type & dd) ;
time_rep_type -subtract_days(const time_rep_type & base, const date_duration_type & dd) ;
time_rep_type -subtract_time_duration(const time_rep_type & base, - const time_duration_type & td) ;
time_rep_type -add_time_duration(const time_rep_type & base, time_duration_type td) ;
time_duration_type -subtract_times(const time_rep_type & lhs, const time_rep_type & rhs) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::starts_with — 'Starts with' predicate
--template<typename Range1T, typename Range2T, typename PredicateT> - bool starts_with(const Range1T & Input, const Range2T & Test, - PredicateT Comp); -template<typename Range1T, typename Range2T> - bool starts_with(const Range1T & Input, const Range2T & Test);
This predicate holds when the test string 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
-An element comparison predicate
An input sequence
A test sequence
Returns:
-
- The result of the test
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::static_local_time_adjustor — Embed the rules for local time adjustments at compile time.
-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) ; -};
static_local_time_adjustor
public static functionstime_duration_type utc_to_local_offset(const time_type & t) ;-
-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
-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.
time_duration_type -local_to_utc_offset(const time_type & t, - date_time::dst_flags dst = date_time::calculate) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::static_visitor — Convenient base type for static visitors.
-template<typename ResultType> -class static_visitor { -public: - // types - typedef ResultType result_type; // Exposes result_type member as required by StaticVisitor concept. -};
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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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)
-
Table of Contents
-- 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. -
-Last revised: April 15, 2005 at 21:05:00 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 11.13. 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
-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 ); - } -}; --
-boost::iterator_range<std::string> simple_finder( - std::string::const_iterator Begin, - std::string::const_iterator End ) -{ - return boost::make_range( Begin, End ); -} --
- 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 11.14. 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
-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; - } -}; --
-std::string simple_formatter( boost::iterator_range<std::string::const_iterator>& Match ) -{ - std::string Temp( Match.begin(), Match.end() ); - return Temp; -} --
Last revised: July 16, 2004 at 09:06:39 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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. -
-Last revised: August 03, 2004 at 17:28:02 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 - range 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 - Boost.Range. This facility allows to access - the elements inside the string in a uniform iterator-based fashion. - 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. RangeT
means that the basic range requirements must hold.
- SequenceT
designates extended sequence requirements.
-
- 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 11.11. 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 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 -
-- 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 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.
-
- 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: -
-- 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
-Last revised: May 14, 2005 at 19:11:09 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 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. -
-- 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. -
-- The library has been successfully compiled and tested with the following compilers: - -
-- - 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.
-
Last revised: July 15, 2004 at 21:47:21 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Table 11.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 11.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 11.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 11.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 11.5. Erase/Replace
-Table 11.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()
- |
-
Table 11.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 11.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() |
-
Table 11.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 |
-
Table 11.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() |
-
Last revised: July 16, 2004 at 09:06:39 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 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. -
-Last revised: July 16, 2004 at 09:06:39 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 RangeT> - OutputIteratorT - to_lower_copy(OutputIteratorT, const RangeT &, - const std::locale & = std::locale()); - template<typename SequenceT> - SequenceT to_lower_copy(const SequenceT &, - const std::locale & = std::locale()); - template<typename WritableRangeT> - void to_lower(WritableRangeT &, const std::locale & = std::locale()); - template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - to_upper_copy(OutputIteratorT, const RangeT &, - const std::locale & = std::locale()); - template<typename SequenceT> - SequenceT to_upper_copy(const SequenceT &, - const std::locale & = std::locale()); - template<typename WritableRangeT> - void to_upper(WritableRangeT &, const std::locale & = std::locale()); - } -}-
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 RangeT> unspecified is_any_of(const RangeT &); - 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 > &); - } -}-
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; - } -}-
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; - } -}-
namespace boost { - namespace algorithm { - enum token_compress_mode_type; - } -}-
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 RangeT> - OutputIteratorT - erase_range_copy(OutputIteratorT, const RangeT &, - const iterator_range< typename range_const_iterator< RangeT >::type > &); - template<typename SequenceT> - SequenceT erase_range_copy(const SequenceT &, - const iterator_range< typename range_const_iterator< SequenceT >::type > &); - template<typename SequenceT> - void erase_range(SequenceT &, - const iterator_range< typename range_iterator< SequenceT >::type > &); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_first_copy(OutputIteratorT, const Range1T &, const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT erase_first_copy(const SequenceT &, const RangeT &); - template<typename SequenceT, typename RangeT> - void erase_first(SequenceT &, const RangeT &); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_first_copy(OutputIteratorT, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - SequenceT ierase_first_copy(const SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - void ierase_first(SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_last_copy(OutputIteratorT, const Range1T &, const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT erase_last_copy(const SequenceT &, const RangeT &); - template<typename SequenceT, typename RangeT> - void erase_last(SequenceT &, const RangeT &); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_last_copy(OutputIteratorT, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - SequenceT ierase_last_copy(const SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - void ierase_last(SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_nth_copy(OutputIteratorT, const Range1T &, const Range2T &, - unsigned int); - template<typename SequenceT, typename RangeT> - SequenceT erase_nth_copy(const SequenceT &, const RangeT &, - unsigned int); - template<typename SequenceT, typename RangeT> - void erase_nth(SequenceT &, const RangeT &, unsigned int); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_nth_copy(OutputIteratorT, const Range1T &, const Range2T &, - unsigned int, const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - SequenceT ierase_nth_copy(const SequenceT &, const RangeT &, - unsigned int, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - void ierase_nth(SequenceT &, const RangeT &, unsigned int, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - erase_all_copy(OutputIteratorT, const Range1T &, const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT erase_all_copy(const SequenceT &, const RangeT &); - template<typename SequenceT, typename RangeT> - void erase_all(SequenceT &, const RangeT &); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - ierase_all_copy(OutputIteratorT, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - SequenceT ierase_all_copy(const SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename SequenceT, typename RangeT> - void ierase_all(SequenceT &, const RangeT &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - erase_head_copy(OutputIteratorT, const RangeT &, 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 RangeT> - OutputIteratorT - erase_tail_copy(OutputIteratorT, const RangeT &, unsigned int); - template<typename SequenceT> - SequenceT erase_tail_copy(const SequenceT &, unsigned int); - template<typename SequenceT> void erase_tail(SequenceT &, unsigned int); - } -}-
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 RangeT, typename FinderT> - iterator_range< typename range_result_iterator< RangeT >::type > - find(RangeT &, FinderT); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_first(Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_first(Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_last(Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_last(Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - find_nth(Range1T &, const Range2T &, unsigned int); - template<typename Range1T, typename Range2T> - iterator_range< typename range_result_iterator< Range1T >::type > - ifind_nth(Range1T &, const Range2T &, unsigned int, - const std::locale & = std::locale()); - template<typename RangeT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_head(RangeT &, unsigned int); - template<typename RangeT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_tail(RangeT &, unsigned int); - template<typename RangeT, typename PredicateT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_token(RangeT &, PredicateT, - token_compress_mode_type = token_compress_off); - } -}-
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 RangeT, typename FinderT, - typename FormatterT> - OutputIteratorT - find_format_copy(OutputIteratorT, const RangeT &, 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 RangeT, typename FinderT, - typename FormatterT> - OutputIteratorT - find_format_all_copy(OutputIteratorT, const RangeT &, 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> - unspecified regex_finder(const basic_regex< CharT, RegexTraitsT > &, - 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); - } -}-
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 RangeT, typename FinderT> - find_iterator< typename range_result_iterator< RangeT >::type > - make_find_iterator(RangeT &, FinderT); - template<typename RangeT, typename FinderT> - split_iterator< typename range_result_iterator< RangeT >::type > - make_split_iterator(RangeT &, FinderT); - } -}-
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 >); - } -}-
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 RangeT> unspecified const_formatter(const RangeT &); - template<typename RangeT> unspecified identity_formatter(); - template<typename RangeT> unspecified empty_formatter(const RangeT &); - } -}-
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 Range1T, typename Range2T, typename PredicateT> - bool starts_with(const Range1T &, const Range2T &, PredicateT); - template<typename Range1T, typename Range2T> - bool starts_with(const Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - bool istarts_with(const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename Range1T, typename Range2T, typename PredicateT> - bool ends_with(const Range1T &, const Range2T &, PredicateT); - template<typename Range1T, typename Range2T> - bool ends_with(const Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - bool iends_with(const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename Range1T, typename Range2T, typename PredicateT> - bool contains(const Range1T &, const Range2T &, PredicateT); - template<typename Range1T, typename Range2T> - bool contains(const Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - bool icontains(const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename Range1T, typename Range2T, typename PredicateT> - bool equals(const Range1T &, const Range2T &, PredicateT); - template<typename Range1T, typename Range2T> - bool equals(const Range1T &, const Range2T &); - template<typename Range1T, typename Range2T> - bool iequals(const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename RangeT, typename PredicateT> - bool all(const RangeT &, PredicateT); - } -}-
Defines regex variants of the algorithms.
-namespace boost { - namespace algorithm { - template<typename RangeT, typename CharT, typename RegexTraitsT> - iterator_range< typename range_result_iterator< RangeT >::type > - find_regex(RangeT &, const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT, typename FormatStringTraitsT, - typename FormatStringAllocatorT> - OutputIteratorT - replace_regex_copy(OutputIteratorT, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - SequenceT replace_regex_copy(const SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - void replace_regex(SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT, typename FormatStringTraitsT, - typename FormatStringAllocatorT> - OutputIteratorT - replace_all_regex_copy(OutputIteratorT, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - SequenceT replace_all_regex_copy(const SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT, - typename FormatStringTraitsT, typename FormatStringAllocatorT> - void replace_all_regex(SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - const std::basic_string< CharT, FormatStringTraitsT, FormatStringAllocatorT > &, - match_flag_type = match_default|format_default); - template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT> - OutputIteratorT - erase_regex_copy(OutputIteratorT, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT> - SequenceT erase_regex_copy(const SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT> - void erase_regex(SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename OutputIteratorT, typename RangeT, typename CharT, - typename RegexTraitsT> - OutputIteratorT - erase_all_regex_copy(OutputIteratorT, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT> - SequenceT erase_all_regex_copy(const SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceT, typename CharT, typename RegexTraitsT> - void erase_all_regex(SequenceT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceSequenceT, typename RangeT, typename CharT, - typename RegexTraitsT> - SequenceSequenceT & - find_all_regex(SequenceSequenceT &, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - template<typename SequenceSequenceT, typename RangeT, typename CharT, - typename RegexTraitsT> - SequenceSequenceT & - split_regex(SequenceSequenceT &, const RangeT &, - const basic_regex< CharT, RegexTraitsT > &, - match_flag_type = match_default); - } -}-
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> - unspecified regex_finder(const basic_regex< CharT, RegexTraitsT > &, - 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); - } -}-
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 Range1T, typename Range2T> - OutputIteratorT - replace_range_copy(OutputIteratorT, const Range1T &, - const iterator_range< typename range_const_iterator< Range1T >::type > &, - const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT replace_range_copy(const SequenceT &, - const iterator_range< typename range_const_iterator< SequenceT >::type > &, - const RangeT &); - template<typename SequenceT, typename RangeT> - void replace_range(SequenceT &, - const iterator_range< typename range_iterator< SequenceT >::type > &, - const RangeT &); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_first_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_first_copy(const SequenceT &, const Range1T &, - const Range2T &); - template<typename SequenceT, typename Range1T, typename Range2T> - void replace_first(SequenceT &, const Range1T &, const Range2T &); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_first_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range2T, typename Range1T> - SequenceT ireplace_first_copy(const SequenceT &, const Range2T &, - const Range1T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_first(SequenceT &, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_last_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_last_copy(const SequenceT &, const Range1T &, - const Range2T &); - template<typename SequenceT, typename Range1T, typename Range2T> - void replace_last(SequenceT &, const Range1T &, const Range2T &); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_last_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_last_copy(const SequenceT &, const Range1T &, - const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_last(SequenceT &, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_nth_copy(OutputIteratorT, const Range1T &, const Range2T &, - unsigned int, const Range3T &); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_nth_copy(const SequenceT &, const Range1T &, - unsigned int, const Range2T &); - template<typename SequenceT, typename Range1T, typename Range2T> - void replace_nth(SequenceT &, const Range1T &, unsigned int, - const Range2T &); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_nth_copy(OutputIteratorT, const Range1T &, const Range2T &, - unsigned int, const Range3T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_nth_copy(const SequenceT &, const Range1T &, - unsigned int, const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_nth(SequenceT &, const Range1T &, unsigned int, - const Range2T &, const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - replace_all_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT replace_all_copy(const SequenceT &, const Range1T &, - const Range2T &); - template<typename SequenceT, typename Range1T, typename Range2T> - void replace_all(SequenceT &, const Range1T &, const Range2T &); - template<typename OutputIteratorT, typename Range1T, typename Range2T, - typename Range3T> - OutputIteratorT - ireplace_all_copy(OutputIteratorT, const Range1T &, const Range2T &, - const Range3T &, const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - SequenceT ireplace_all_copy(const SequenceT &, const Range1T &, - const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceT, typename Range1T, typename Range2T> - void ireplace_all(SequenceT &, const Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - replace_head_copy(OutputIteratorT, const Range1T &, unsigned int, - const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT replace_head_copy(const SequenceT &, unsigned int, - const RangeT &); - template<typename SequenceT, typename RangeT> - void replace_head(SequenceT &, unsigned int, const RangeT &); - template<typename OutputIteratorT, typename Range1T, typename Range2T> - OutputIteratorT - replace_tail_copy(OutputIteratorT, const Range1T &, unsigned int, - const Range2T &); - template<typename SequenceT, typename RangeT> - SequenceT replace_tail_copy(const SequenceT &, unsigned int, - const RangeT &); - template<typename SequenceT, typename RangeT> - void replace_tail(SequenceT &, unsigned int, const RangeT &); - } -}-
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_const_time_erase; - template<typename T> class has_const_time_insert; - template<typename T> class has_native_replace; - template<typename T> class has_stable_iterators; - } -}-
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 Range1T, typename Range2T> - SequenceSequenceT & - find_all(SequenceSequenceT &, Range1T &, const Range2T &); - template<typename SequenceSequenceT, typename Range1T, typename Range2T> - SequenceSequenceT & - ifind_all(SequenceSequenceT &, Range1T &, const Range2T &, - const std::locale & = std::locale()); - template<typename SequenceSequenceT, typename RangeT, typename PredicateT> - SequenceSequenceT & - split(SequenceSequenceT &, RangeT &, PredicateT, - token_compress_mode_type = token_compress_off); - } -}-
This file includes sequence traits for stl containers.
-Cumulative include for string_algo library
-Cumulative include for string_algo library. In addtion to string.hpp contains also regex-related stuff.
-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 RangeT, typename PredicateT> - OutputIteratorT - trim_left_copy_if(OutputIteratorT, const RangeT &, 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 RangeT, typename PredicateT> - OutputIteratorT - trim_right_copy_if(OutputIteratorT, const RangeT &, 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 RangeT, typename PredicateT> - OutputIteratorT - trim_copy_if(OutputIteratorT, const RangeT &, 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()); - } -}-
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
1.32
-Initial release in Boost
-1.33
-Internal version of collection traits removed, library adapted to Boost.Range
-Last revised: April 15, 2005 at 21:05:00 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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 Boost.Range
- provides a uniform way of handling different string types.
- If there is a need to pass a pair of iterators,
- boost::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.
-
- 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
.
-
- 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()
- 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
.
-
- 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 boost::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
- Boost.Range.
-
- The following lines transform the result. Notice that
- boost::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
.
-
- 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.
-
- 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 boost::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_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_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 range. -
-
- See the reference in boost/algorithm/string/find_iterator.hpp
.
-
- 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
.
-
Last revised: May 14, 2005 at 19:11:09 GMT |
-Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::string_parse_tree — Recursive data structure to allow efficient parsing of various strings.
-template<typename charT> -struct string_parse_tree { - // types - typedef std::multimap< charT, string_parse_tree > ptree_coll; - typedef ptree_coll::value_type value_type; - typedef ptree_coll::iterator iterator; - typedef ptree_coll::const_iterator const_iterator; - typedef std::basic_string< charT > string_type; - typedef std::vector< std::basic_string< charT > > collection_type; - typedef parse_match_result< charT > parse_match_result_type; - - // construct/copy/destruct - string_parse_tree(collection_type, unsigned int = 0); - string_parse_tree(short = -1); - - // public member functions - void insert(const string_type &, unsigned short) ; - short match(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &, parse_match_result_type &, - unsigned int &) const; - parse_match_result_type - match(std::istreambuf_iterator< charT > &, - std::istreambuf_iterator< charT > &) const; - void printme(std::ostream &, int &) ; - void print(std::ostream &) ; - void printmatch(std::ostream &, charT) ; - - ptree_coll m_next_chars; - short m_value; -};
This class provides a quick lookup by building what amounts to a tree data structure. It also features a match function which can can handle nasty input interators by caching values as it recurses the tree so that it can backtrack as needed.
-string_parse_tree
construct/copy/destructstring_parse_tree(collection_type names, unsigned int starting_point = 0);-
Parameter "starting_point" desingates where the numbering begins. A starting_point of zero will start the numbering at zero (Sun=0, Mon=1, ...) were a starting_point of one starts the numbering at one (Jan=1, Feb=2, ...). The default is zero, negative vaules are not allowed
-string_parse_tree(short value = -1);
string_parse_tree
public member functionsvoid insert(const string_type & s, unsigned short value) ;
short match(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end, - parse_match_result_type & result, unsigned int & level) const;-
Must check match_results::has_remaining() after match() is called. This is required so the user can determine if stream iterator is already pointing to the expected character or not (match() might advance sitr to next char in stream).
-A parse_match_result that has been returned from a failed match attempt can be sent in to the match function of a different string_parse_tree to attempt a match there. Use the iterators for the partially consumed stream, the parse_match_result object, and '0' for the level parameter.
-parse_match_result_type -match(std::istreambuf_iterator< charT > & sitr, - std::istreambuf_iterator< charT > & stream_end) const;-
Must check match_results::has_remaining() after match() is called. This is required so the user can determine if stream iterator is already pointing to the expected character or not (match() might advance sitr to next char in stream).
-void printme(std::ostream & os, int & level) ;
void print(std::ostream & os) ;
void printmatch(std::ostream & os, charT c) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::subsecond_duration — Template for instantiating derived adjusting durations.
-template<typename base_duration, boost::int64_t frac_of_second> -class subsecond_duration { -public: - // types - typedef base_duration::traits_type traits_type; - - // construct/copy/destruct - subsecond_duration(boost::int64_t); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::tail_finder — "Tail" finder
--unspecified tail_finder(unsigned int N);
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
-The size of the head
Returns:
-
- An instance of the tail_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::thread —
The thread class represents threads of - execution, and provides the functionality to create and manage - threads within the 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.
--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(); -};
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 to schedule transitions between thread states is - unspecified.
-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/destructthread();-
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.
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.
~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
comparisonbool 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.
bool operator!=( rhs) const;-
Requires:
-
- The thread is non-terminated or *this
- is joinable.
Returns:
-
- !(*this==rhs)
.
thread
modifiervoid 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
staticstatic void sleep(const xtime& xt);-
Effects:
-
- The current thread of execution blocks until
- xt
is reached.
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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
William E. Kempf was the architect, designer, and implementor of - .
-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 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 - . 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.
-Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- How you build the 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 makes use of . - In general you should refer to the documentation for . - This document will only supply you with some simple usage examples for how to - use bjam to build and test . 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 , as well as for building their own projects using - . -
-- To build the libraries using , 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 library. -
-- The Jamfile supplied with 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 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 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. -
-Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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. -
-- These macros are defined by 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 and that - threading support has been enabled in a platform specific manner. For instance, - on the Win32 platform there's an implementation for - 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. - | -
- These macros are defined by 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_HAS_PTHREADS | -- Indicates that the platform has the POSIX pthreads libraries, and that - they should be used to implement . - | -
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(). - | -
Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::thread_group — - The thread_group class provides a container - for easy grouping of threads to simplify several common thread - creation and management idioms. -
--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(); -};
thread_group
construct/copy/destructthread_group();-
Effects: - - Constructs an empty thread_group - container.
-~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
modifierthread* 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.
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.
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.
void join_all();-
Effects:
-
- Calls join()
on each of the managed
- thread objects.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::thread_resource_error —
The thread_resource_error class - defines an exception type that is thrown by constructors in the - library when thread-related resources can not be - acquired.
--class thread_resource_error : public std::runtime_error { -public: - // construct/copy/destruct - thread_resource_error(); -};
thread_resource_error is used - only when thread-related resources cannot be acquired; memory - allocation failures are indicated by - std::bad_alloc.
- -- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::thread_specific_ptr — - The thread_specific_ptr class defines - an interface for using thread specific storage. -
--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; -};
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: -
-thread_specific_ptr
construct/copy/destructthread_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.
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.
-
~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 functionsT* 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.
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 functionsT* get() const;-
Returns:
-
- The object stored in thread specific storage for
- the current thread for *this
.
Notes:
-
- Each thread initially returns 0.
T* operator->() const;-
Returns:
-
- this->get()
.
T& operator*()() const;-
Requires:
-
- this->get() != 0
Returns:
-
- this->get()
.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
-Table of Contents
-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!
Beyond the errors which can occur in single-threaded programs, - multithreaded programs are subject to additional errors: -
-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 design - attempts to minimize these errors, but they will still occur unless the - programmer proactively designs to avoid them.
-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.
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. Many important multithreading programming - considerations (independent of threading library) are discussed in - Programming with POSIX Threads.
-Doing some reading before attempting multithreaded designs will - give you a head start toward reliable multithreaded programs.
-Warning: Multithreaded programs such as
- those using 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.
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 .
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.
-destructors never - throw exceptions. Unless otherwise specified, other - functions that do not have - an exception-specification may throw implementation-defined - exceptions.
-In particular,
- 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.
- 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.
Definitions are given in terms of the C++ Standard - . 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 places on a C++ - implementation as defined by the C++ Standard.
-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].
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.
-During the lifetime of a thread, it shall be in one of the following - states:
-Table 12.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 12.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.]
-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 .
-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.
The condition in which a thread is not making sufficient progress in - its work during a given time interval.
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.
The result of certain operations in 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.
-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 12.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.
-[AndrewsSchnieder83] ACM Computing Surveys. No. 1. March, 1983. 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.
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. No. 4. December, 1973. 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 . Addison-WesleyCopyright © 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. No. 10. October, 1974. “Monitors: An Operating System Structuring Concept”. 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. No. 2. December, 1989. 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. Department of Computer Science, Washington University, St. Louis, - Missouri.
Rationale for understanding condition - variables. Note that Alexander Terekhov found some bugs in the - implementation given in this article, so pthreads-win32 and - are even more complicated yet.
-[SchmidtStalRohnertBuschmann] Pattern-Oriented Architecture Volume 2. Patterns for Concurrent and Networked Objects. POSA2. WileyCopyright © 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 - documentation.
-[Stroustrup] The C++ Programming Language. Special Edition. Addison-WesleyCopyright © 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.
-Last revised: July 07, 2005 at 18:06:26 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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).
-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 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 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 - 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 - mutex objects. This helps to - ensure safe usage patterns, especially when code throws exceptions.
-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.
-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 - 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.
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
- , an exception of type
- boost::lock_error
- would be thrown in these cases.
does not currently - provide any mutex objects that use this 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.
-does not currently - provide any mutex objects that use this 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.
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.
-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.
-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.
-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 12.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 - | -
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 12.2. TryMutex Expressions
-Expression | -Effects | -
---|---|
M::scoped_try_lock | -A model of - ScopedTryLock - | -
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 12.3. TimedMutex Expressions
-Expression | -Effects | -
---|---|
M::scoped_timed_lock | -A model of - ScopedTimedLock - | -
currently supplies six models of - Mutex - and its refinements.
-Table 12.4. Mutex Models
-Concept | -Refines | -Models | -
---|---|---|
Mutex | -- | - - - | -
TryMutex | -Mutex | -- - - | -
TimedMutex | -TryMutex | -- - - | -
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 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.
-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 12.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 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: |
-
lk.unlock() |
-
- Throws Unlocks the associated mutex. -Postcondition: |
-
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.
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 12.7. TryLock Expressions
-Expression | -Effects | -
---|---|
lk.try_lock() |
-
- Throws Makes a
- non-blocking attempt to lock the associated mutex object,
- returning |
-
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.
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 12.9. TimedLock Expressions
-Expression | -Effects | -
---|---|
lk.timed_lock(t) |
-
- Throws Makes a blocking attempt
- to lock the associated mutex object, and returns |
-
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 12.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()
- |
-
currently supplies twelve models of - Lock - and its refinements.
-Table 12.11. Lock Models
-Concept | -Refines | -Models | -
---|---|---|
Lock | -- | - |
ScopedLock | -Lock | -
-
|
-
TryLock | -Lock | -- |
ScopedTryLock | -TryLock | -
-
|
-
TimedLock | -TryLock | -- |
ScopedTimedLock | -TimedLock | -
-
|
-
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 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 - 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 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 - 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 - read/write mutex objects. This helps to - ensure safe usage patterns, especially when code throws exceptions.
-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.
-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 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. -
-does not currently provide any read/write mutex objects - that use this strategy. A successful implementation of this locking strategy - may require - thread identification. -
-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 , 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
- |
-
does not currently provide any read/write mutex objects - that use this strategy. A successful implementation of this locking strategy - may require - thread identification. -
-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 | -
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. -
-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.
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 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.
-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, supports lock promotion
- through promote()
, try_promote()
,
- and timed_promote()
operations.
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, supports lock demotion
- through demote()
, try_demote()
,
- and timed_demote()
operations.
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. -
-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 |
-
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 |
-
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 |
-
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 |
-
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.
-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.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. | -
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 12.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. | -
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 12.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. | -
currently supplies three models of - ReadWriteMutex - and its refinements.
-Table 12.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 |
-
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 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.
-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 12.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 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: |
-
lk.write_lock() |
-
- Throws 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: |
-
lk.demote() |
-
- Throws Converts the lock held on the associated read/write mutex - object from a write-lock to a read-lock without releasing - the lock. -Postcondition: |
-
lk.promote() |
-
- Throws 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 Unlocks the associated read/write mutex. -Postcondition: |
-
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 12.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() . |
-
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 12.18. TryReadWriteLock Expressions
-Expression | -Effects | -
---|---|
lk.try_read_lock() |
-
- Throws Makes a non-blocking attempt to read-lock the associated read/write
- mutex object, returning |
-
lk.try_write_lock() |
-
- Throws Makes a non-blocking attempt to write-lock the associated read/write
- mutex object, returning |
-
lk.try_demote() |
-
- Throws 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 |
-
lk.try_promote() |
-
- Throws 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 |
-
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 12.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 . |
-
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 12.20. TimedReadWriteLock Expressions
-Expression | -Effects | -
---|---|
lk.timed_read_lock(t) |
-
- Throws Makes a blocking attempt to read-lock the associated read/write mutex object,
- and returns |
-
lk.timed_write_lock(t) |
-
- Throws Makes a blocking attempt to write-lock the associated read/write mutex object,
- and returns |
-
lk.timed_demote(t) |
-
- Throws 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 |
-
lk.timed_promote(t) |
-
- Throws 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 |
-
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 12.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) . |
-
currently supplies six models of - ReadWriteLock - and its refinements.
-Table 12.22. Lock Models
-Concept | -Refines | -Models | -
---|---|---|
ReadWriteLock | -- | - |
ScopedReadWriteLock | -ReadWriteLock | -
-
|
-
TryReadWriteLock | -ReadWriteLock | -- |
ScopedTryReadWriteLock | -TryReadWriteLock | -
-
|
-
TimedReadWriteLock | -TryReadWriteLock | -- |
ScopedTimedReadWriteLock | -TimedReadWriteLock | -
|
-
Last revised: November 28, 2004 at 04:29:36 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 library is an attempt to define a portable interface - for writing parallel processes in C++.
-The 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. -
-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.
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.
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, - 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.
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. 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.
Another goal of 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." - 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 - shall go through several growth cycles. Each phase in its - development shall be roughly documented here.
-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 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.
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 adds the boost::thread
and
- boost::thread_specific_ptr
types. With these
- additions the library can be considered minimal but
- complete.
Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-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 modeled after (specific library - name)? |
-
- | It wasn't. 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 design is very much in the spirit - of C++, and thus doesn't model such C based APIs. |
-
-3. - | -Why wasn't 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 . |
-
-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 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 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 |
-
- | 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 and . - |
-
-9. - | -Why isn't thread cancellation or termination provided? |
-
- | There's a valid need for thread termination, so at some point - 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. |
-
Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- 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: -
-Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
This page explains the rationale behind various design decisions in the - 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.
-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 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.
-The library supplies a set of low level primitives for - writing multithreaded programs, such as mutexes and condition variables. In - fact, the first release of 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 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.
-Programmers who are used to multithreaded programming issues will - quickly note that the 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 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.
-Programmers who are used to C libraries for multithreaded programming
- are likely to wonder why 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.
- -- void foo() - { - thread = create_thread(&bar); - join(thread); - } --
- void foo() - { - for (int i=0; i<NUM_THREADS; ++i) - create_thread(&bar); - } --
- 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(); - } --
- void foo() - { - thread = create_thread(&bar); - manager.owns(thread); - } --
- 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.
-- void foo() - { - thread thrd(&bar); - } - void foo() - { - thread_ref thrd = create_thread(&bar); - } --
- void foo() - { - thread thrd(&bar); - thrd.join(); - } - void foo() - { - thread_ref thrd = - create_thread(&bar);thrd->join(); - } --
- 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); - } --
- 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(); - } --
- void foo() - { - thread thrd* = new thread(&bar); - manager.owns(thread); - } - void foo() - { - thread_ref thrd = create_thread(&bar); - manager.owns(thrd); - } --
- 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 library has gone with a noncopyable design.
-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 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 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]
-Last revised: July 17, 2004 at 04:33:59 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
namespace boost { - class barrier; -}-
namespace boost { - class condition; -}-
namespace boost { - class lock_error; - class thread_resource_error; -}-
namespace boost { - class mutex; - class try_mutex; - class timed_mutex; -}-
- -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&);
-}
-namespace boost { - class recursive_mutex; - class recursive_try_mutex; - class recursive_timed_mutex; -}-
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; - } -}-
namespace boost { - class thread; - class thread_group; -}-
namespace boost { - class thread_specific_ptr; -}-
namespace boost { - enum xtime_clock_types; - - struct xtime; - int xtime_get(xtime*, int); -}-
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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!
-The option to link 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 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
- users, this decision was reversed.
On non-Win32 platforms: - To choose the dynamically linked version of - 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 . - - Note for advanced users: 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.
-A new class, boost::barrier
, was added.
New classes,
- boost::read_write_mutex
,
- boost::try_read_write_mutex
, and
- boost::timed_read_write_mutex
- were added.
-
-
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.
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.
Last revised: August 05, 2004 at 18:07:20 GMT |
-Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_facet —
-template<typename time_type, typename CharT, - typename OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > > -class time_facet : public boost::date_time::date_facet< time_type::date_type, CharT, OutItrT > -{ -public: - // types - typedef time_type::date_type date_type; - typedef time_type::time_duration_type time_duration_type; - typedef boost::date_time::period< time_type, time_duration_type > period_type; - typedef boost::date_time::date_facet< typename time_type::date_type, CharT, OutItrT > base_type; - typedef base_type::string_type string_type; - typedef base_type::char_type char_type; - typedef base_type::period_formatter_type period_formatter_type; - typedef base_type::special_values_formatter_type special_values_formatter_type; - typedef base_type::date_gen_formatter_type date_gen_formatter_type; - - // construct/copy/destruct - time_facet(::size_t = 0); - time_facet(const char_type *, - period_formatter_type = period_formatter_type(), - const special_values_formatter_type & = special_values_formatter_type(), - date_gen_formatter_type = date_gen_formatter_type(), - ::size_t = 0); - - // public member functions - std::locale::id & __get_id(void) const; - void time_duration_format(const char_type *const) ; - virtual void set_iso_format() ; - virtual void set_iso_extended_format() ; - OutItrT put(OutItrT, std::ios_base &, char_type, const time_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const time_duration_type &) const; - OutItrT put(OutItrT, std::ios_base &, char_type, const period_type &) const; - - // protected static functions - string_type fractional_seconds_as_string(const time_duration_type &, bool) ; - - static const char_type * fractional_seconds_format; - static const char_type * fractional_seconds_or_none_format; - static const char_type * seconds_with_fractional_seconds_format; - static const char_type * seconds_format; - static const char_type * standard_format; - static const char_type * zone_abbrev_format; - static const char_type * zone_name_format; - static const char_type * zone_iso_format; - static const char_type * zone_iso_extended_format; - static const char_type * posix_zone_string_format; - static const char_type * duration_seperator; - static const char_type * duration_sign_always; - static const char_type * duration_sign_negative_only; - static const char_type * negative_sign; - static const char_type * positive_sign; - static const char_type * iso_time_format_specifier; - static const char_type * iso_time_format_extended_specifier; - static const char_type * default_time_format; - static const char_type * default_time_duration_format; - static std::locale::id id; -};
Facet used for format-based output of time types This class provides for the use of format strings to output times. In addition to the flags for formatting date elements, the following are the allowed format flags:
-x X => default format - enables addition of more flags to default (ie. "%x %X %z")
f => fractional seconds ".123456"
F => fractional seconds or none: like frac sec but empty if frac sec == 0
s => seconds w/ fractional sec "02.123" (this is the same as "%S%f)
S => seconds "02"
z => abbreviated time zone "EDT"
Z => full time zone name "Eastern Daylight Time"
time_facet
construct/copy/destructtime_facet(::size_t a_ref = 0);
time_facet(const char_type * a_format, - period_formatter_type period_formatter = period_formatter_type(), - const special_values_formatter_type & special_value_formatter = special_values_formatter_type(), - date_gen_formatter_type dg_formatter = date_gen_formatter_type(), - ::size_t a_ref = 0);
time_facet
public member functionsstd::locale::id & __get_id(void ) const;
void time_duration_format(const char_type *const format) ;
virtual void set_iso_format() ;
virtual void set_iso_extended_format() ;
OutItrT put(OutItrT a_next, std::ios_base & a_ios, char_type a_fill, - const time_type & a_time) const;
OutItrT put(OutItrT a_next, std::ios_base & a_ios, char_type a_fill, - const time_duration_type & a_time_dur) const;
OutItrT put(OutItrT next, std::ios_base & a_ios, char_type fill, - const period_type & p) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_formats —
-template<typename CharT> -struct time_formats { - // types - typedef CharT char_type; - - static const char_type fractional_seconds_format; - static const char_type fractional_seconds_or_none_format; - static const char_type seconds_with_fractional_seconds_format; - static const char_type seconds_format; - static const char_type standard_format; - static const char_type zone_abbrev_format; - static const char_type zone_name_format; - static const char_type zone_iso_format; - static const char_type zone_iso_extended_format; - static const char_type posix_zone_string_format; - static const char_type duration_sign_negative_only; - static const char_type duration_sign_always; - static const char_type duration_seperator; - static const char_type negative_sign; - static const char_type positive_sign; - static const char_type iso_time_format_specifier; - static const char_type iso_time_format_extended_specifier; - static const char_type default_time_format; - static const char_type default_time_input_format; - static const char_type default_time_duration_format; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_from_ftime — Create a time object from an initialized FILETIME struct.
--template<typename time_type> time_type time_from_ftime(const FILETIME & ft);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_input_facet — Facet for format-based input.
-template<typename time_type, typename CharT, - typename InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > > -class time_input_facet : public boost::date_time::date_input_facet< time_type::date_type, CharT, InItrT > -{ -public: - // types - typedef time_type::date_type date_type; - typedef time_type::time_duration_type time_duration_type; - typedef time_duration_type::fractional_seconds_type fracional_seconds_type; - typedef boost::date_time::period< time_type, time_duration_type > period_type; - typedef boost::date_time::date_input_facet< typename time_type::date_type, CharT, InItrT > base_type; - typedef base_type::duration_type date_duration_type; - typedef base_type::year_type year_type; - typedef base_type::month_type month_type; - typedef base_type::day_type day_type; - typedef base_type::string_type string_type; - typedef string_type::const_iterator const_itr; - typedef base_type::char_type char_type; - typedef base_type::format_date_parser_type format_date_parser_type; - typedef base_type::period_parser_type period_parser_type; - typedef base_type::special_values_parser_type special_values_parser_type; - typedef base_type::date_gen_parser_type date_gen_parser_type; - typedef base_type::special_values_parser_type::match_results match_results; - - // construct/copy/destruct - time_input_facet(const string_type &, ::size_t = 0); - time_input_facet(const string_type &, const format_date_parser_type &, - const special_values_parser_type &, - const period_parser_type &, const date_gen_parser_type &, - ::size_t = 0); - time_input_facet(::size_t = 0); - - // public member functions - void time_duration_format(const char_type *const) ; - virtual void set_iso_format() ; - virtual void set_iso_extended_format() ; - InItrT get(InItrT &, InItrT &, std::ios_base &, period_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, time_duration_type &) const; - InItrT get(InItrT &, InItrT &, std::ios_base &, time_type &) const; - InItrT get_local_time(InItrT &, InItrT &, std::ios_base &, time_type &, - string_type &) const; - - // protected member functions - InItrT get(InItrT &, InItrT &, std::ios_base &, time_type &, string_type &, - bool) const; - template<typename temporal_type> - InItrT check_special_value(InItrT &, InItrT &, temporal_type &, - char_type = '\0') const; - void parse_frac_type(InItrT &, InItrT &, fracional_seconds_type &) const; - - // private member functions - template<typename int_type> - int_type decimal_adjust(int_type, const unsigned short) const; - - static const char_type * fractional_seconds_format; - static const char_type * fractional_seconds_or_none_format; - static const char_type * seconds_with_fractional_seconds_format; - static const char_type * seconds_format; - static const char_type * standard_format; - static const char_type * zone_abbrev_format; - static const char_type * zone_name_format; - static const char_type * zone_iso_format; - static const char_type * zone_iso_extended_format; - static const char_type * duration_seperator; - static const char_type * iso_time_format_specifier; - static const char_type * iso_time_format_extended_specifier; - static const char_type * default_time_input_format; - static const char_type * default_time_duration_format; - static std::locale::id id; -};
time_input_facet
construct/copy/destructtime_input_facet(const string_type & format, ::size_t a_ref = 0);
time_input_facet(const string_type & format, - const format_date_parser_type & date_parser, - const special_values_parser_type & sv_parser, - const period_parser_type & per_parser, - const date_gen_parser_type & date_gen_parser, - ::size_t a_ref = 0);
time_input_facet(::size_t a_ref = 0);
time_input_facet
public member functionsvoid time_duration_format(const char_type *const format) ;
virtual void set_iso_format() ;
virtual void set_iso_extended_format() ;
InItrT get(InItrT & sitr, InItrT & stream_end, std::ios_base & a_ios, - period_type & p) const;
InItrT get(InItrT & sitr, InItrT & stream_end, std::ios_base & a_ios, - time_duration_type & td) const;
InItrT get(InItrT & sitr, InItrT & stream_end, std::ios_base & a_ios, - time_type & t) const;
InItrT get_local_time(InItrT & sitr, InItrT & stream_end, - std::ios_base & a_ios, time_type & t, - string_type & tz_str) const;
time_input_facet
protected member functionsInItrT get(InItrT & sitr, InItrT & stream_end, std::ios_base & a_ios, - time_type & t, string_type & tz_str, bool time_is_local) const;
template<typename temporal_type> - InItrT check_special_value(InItrT & sitr, InItrT & stream_end, - temporal_type & tt, char_type c = '\0') const;-
First character may have been consumed during original parse attempt. Parameter 'c' should be a copy of that character. Throws ios_base::failure if parse fails.
-void parse_frac_type(InItrT & sitr, InItrT & stream_end, - fracional_seconds_type & frac) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_itr — Simple time iterator skeleton class.
-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 &) ; -};
time_itr
public member functionstime_itr & operator++() ;
time_itr & operator--() ;
time_type operator *() ;
time_type * operator->() ;
bool operator<(const time_type & t) ;
bool operator<=(const time_type & t) ;
bool operator!=(const time_type & t) ;
bool operator==(const time_type & t) ;
bool operator>(const time_type & t) ;
bool operator>=(const time_type & t) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::time_label_invalid — simple exception for when time label given cannot exist
--struct time_label_invalid { - // construct/copy/destruct - time_label_invalid(std::string = ""); - - // public member functions -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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) ; -};
time_resolution_traits
public static functionsfrac_sec_type::int_type as_number(typename frac_sec_type::impl_type i) ;
bool is_adapted() ;
time_resolutions resolution() ;
unsigned short num_fractional_digits() ;
fractional_seconds_type res_adjust() ;
tick_type to_tick_count(hour_type hours, min_type minutes, sec_type seconds, - fractional_seconds_type fs) ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::local_time::time_zone — A real time zone.
--class time_zone { -public: - // types - typedef boost::posix_time::time_duration time_duration_type; - typedef time_zone_base base_type; - typedef base_type::string_type string_type; - typedef base_type::stringstream_type stringstream_type; - - // construct/copy/destruct - time_zone(const time_zone_names &, const time_duration_type &, - const dst_adjustment_offsets &, - boost::shared_ptr< dst_calc_rule >); - ~time_zone(); - - // public member functions - virtual std::string dst_zone_abbrev() const; - virtual std::string std_zone_abbrev() const; - virtual std::string dst_zone_name() const; - virtual std::string std_zone_name() const; - virtual bool has_dst() const; - virtual posix_time::ptime dst_local_start_time(gregorian::greg_year) const; - virtual posix_time::ptime dst_local_end_time(gregorian::greg_year) const; - virtual time_duration_type base_utc_offset() const; - virtual time_duration_type dst_offset() const; - virtual string_type to_posix_string() const; -};
time_zone
public member functionsvirtual std::string dst_zone_abbrev() const;
virtual std::string std_zone_abbrev() const;
virtual std::string dst_zone_name() const;
virtual std::string std_zone_name() const;
virtual bool has_dst() const;
virtual posix_time::ptime dst_local_start_time(gregorian::greg_year y) const;
virtual posix_time::ptime dst_local_end_time(gregorian::greg_year y) const;
virtual time_duration_type base_utc_offset() const;
virtual time_duration_type dst_offset() const;
virtual string_type to_posix_string() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_zone_base — Interface class for dynamic time zones.
-template<typename time_type, typename CharT = char> -class time_zone_base { -public: - // types - typedef std::basic_string< CharT > string_type; - typedef std::basic_stringstream< CharT > stringstream_type; - typedef time_type::date_type::year_type year_type; - typedef time_type::time_duration_type time_duration_type; - - // construct/copy/destruct - time_zone_base(); - ~time_zone_base(); - - // public member functions - virtual string_type dst_zone_abbrev() const; - virtual string_type std_zone_abbrev() const; - virtual string_type dst_zone_name() const; - virtual string_type std_zone_name() const; - virtual bool has_dst() const; - virtual time_type dst_local_start_time(year_type) const; - virtual time_type dst_local_end_time(year_type) const; - virtual time_duration_type base_utc_offset() const; - virtual time_duration_type dst_offset() const; - virtual string_type to_posix_string() const; -};
This class represents the base interface for all timezone representations. Subclasses may provide different systems for identifying a particular zone. For example some may provide a geographical based zone construction while others may specify the offset from GMT. Another possible implementation would be to convert from POSIX timezone strings. Regardless of the construction technique, this is the interface that these time zone types must provide.
-Note that this class is intended to be used as a shared resource (hence the derivation from boost::counted_base.
- -time_zone_base
public member functionsvirtual string_type dst_zone_abbrev() const;
virtual string_type std_zone_abbrev() const;
virtual string_type dst_zone_name() const;
virtual string_type std_zone_name() const;
virtual bool has_dst() const;
virtual time_type dst_local_start_time(year_type y) const;
virtual time_type dst_local_end_time(year_type y) const;
virtual time_duration_type base_utc_offset() const;
virtual time_duration_type dst_offset() const;
virtual string_type to_posix_string() const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::time_zone_names_base — Base type that holds various string names for timezone output.
-template<typename CharT = char> -class time_zone_names_base { -public: - // types - typedef std::basic_string< CharT > string_type; - - // construct/copy/destruct - time_zone_names_base(const string_type &, const string_type &, - const string_type &, const string_type &); - - // public member functions - string_type dst_zone_abbrev() const; - string_type std_zone_abbrev() const; - string_type dst_zone_name() const; - string_type std_zone_name() const; -};
Class that holds various types of strings used for timezones. For example, for the western United States there is the full name: Pacific Standard Time and the abbreviated name: PST. During daylight savings there are additional names: Pacific Daylight Time and PDT. CharT Allows class to support different character types
- - -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::timed_mutex —
The timed_mutex class is a model of the - TimedMutex concept.
--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(); -};
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 , 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/destructtimed_mutex();-
Effects:
-
- Constructs a timed_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::timed_read_write_mutex —
The timed_read_write_mutex class is a model of the - TimedReadWriteMutex concept.
--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(); -};
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 , 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. -
-timed_read_write_mutex
construct/copy/destructtimed_read_write_mutex(boost::read_write_scheduling_policy count);-
Effects:
-
- Constructs a timed_read_write_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::to_lower — Convert to lower case.
--template<typename WritableRangeT> - void to_lower(WritableRangeT & Input, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::to_lower_copy — Convert to lower case.
--template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - to_lower_copy(OutputIteratorT Output, const RangeT & Input, - const std::locale & Loc = std::locale()); -template<typename SequenceT> - SequenceT to_lower_copy(const SequenceT & Input, - const std::locale & Loc = std::locale());
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
-An input range
A locale used for conversion
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::to_upper — Convert to upper case.
--template<typename WritableRangeT> - void to_upper(WritableRangeT & Input, - const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::to_upper_copy — Convert to upper case.
--template<typename OutputIteratorT, typename RangeT> - OutputIteratorT - to_upper_copy(OutputIteratorT Output, const RangeT & Input, - const std::locale & Loc = std::locale()); -template<typename SequenceT> - SequenceT to_upper_copy(const SequenceT & Input, - const std::locale & Loc = std::locale());
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
-An input range
A locale used for conversion
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::token_finder — "Token" finder
--template<typename PredicateT> - unspecified token_finder(PredicateT Pred, - token_compress_mode_type eCompress = token_compress_off);
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
-An element selection predicate
Compress flag
Returns:
-
- An instance of the token_finder
object
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::signals::trackable — Enables safe use of multicast callbacks.
--class trackable { -public: - // construct/copy/destruct - trackable(); - trackable(const trackable&); - trackable& operator=(const trackable&); - ~trackable(); -};
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/destructtrackable();-
Effects:
-
- Sets the list of connected slots to empty.
Throws:
-
- Will not throw.
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.
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.
~trackable();-
Effects: - - Disconnects all signal/slot connections that - contain a pointer or reference to this trackable object that - can be found by - visit_each.
-- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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)
Table of Contents
- -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.
Last revised: July 25, 2004 at 03:01:38 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
- -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); - } -}-
namespace boost { - namespace logic { - } -}-
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_ostream< CharT, Traits > & - operator<<(std::basic_ostream< CharT, Traits > &, unspecified); - template<typename CharT, typename Traits> - std::basic_istream< CharT, Traits > & - operator>>(std::basic_istream< CharT, Traits > &, tribool &); - } -}-
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Test | -Type | -Description | -If failing... | -
---|---|---|---|
- | run |
-Test all features of the
- |
-- |
- | run |
-Test the use of the
- |
-- |
- | run |
-Test tribool input/output. |
-- |
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 comparetribool
s 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 -}
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
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, newindeterminate_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.
- | Copyright © 2002-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim — Trim.
--template<typename SequenceT> - void trim(SequenceT & Input, const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_copy — Trim.
--template<typename SequenceT> - SequenceT trim_copy(const SequenceT & Input, - const std::locale & Loc = std::locale());
Remove all leading and trailing spaces from the input. The result is a trimmed copy of the input
- -Parameters
-An input sequence
A locale used for 'space' classification
Returns:
-
- A trimmed copy of the input
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_copy_if — Trim - parametric.
--template<typename OutputIteratorT, typename RangeT, typename PredicateT> - OutputIteratorT - trim_copy_if(OutputIteratorT Output, const RangeT & Input, - PredicateT IsSpace); -template<typename SequenceT, typename PredicateT> - SequenceT trim_copy_if(const SequenceT & Input, PredicateT IsSpace);
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
-An input range
An unary predicate identifying spaces
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_if — Trim.
--template<typename SequenceT, typename PredicateT> - void trim_if(SequenceT & Input, PredicateT IsSpace);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_left — Left trim.
--template<typename SequenceT> - void trim_left(SequenceT & Input, const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_left_copy — Left trim - parametric.
--template<typename SequenceT> - SequenceT trim_left_copy(const SequenceT & Input, - const std::locale & Loc = std::locale());
Remove all leading spaces from the input. The result is a trimmed copy of the input.
- -Parameters
-An input sequence
a locale used for 'space' classification
Returns:
-
- A trimmed copy of the input
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_left_copy_if — Left trim - parametric.
--template<typename OutputIteratorT, typename RangeT, typename PredicateT> - OutputIteratorT - trim_left_copy_if(OutputIteratorT Output, const RangeT & Input, - PredicateT IsSpace); -template<typename SequenceT, typename PredicateT> - SequenceT trim_left_copy_if(const SequenceT & Input, PredicateT IsSpace);
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
-An input range
An unary predicate identifying spaces
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_left_if — Left trim.
--template<typename SequenceT, typename PredicateT> - void trim_left_if(SequenceT & Input, PredicateT IsSpace);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_right — Right trim.
--template<typename SequenceT> - void trim_right(SequenceT & Input, const std::locale & Loc = std::locale());
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_right_copy — Right trim.
--template<typename SequenceT> - SequenceT trim_right_copy(const SequenceT & Input, - const std::locale & Loc = std::locale());
Remove all trailing spaces from the input. The result is a trimmed copy of the input
- -Parameters
-An input sequence
A locale used for 'space' classification
Returns:
-
- A trimmed copy of the input
Notes:
-
- This function provides the strong exception-safety guarantee
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_right_copy_if — Right trim - parametric.
--template<typename OutputIteratorT, typename RangeT, typename PredicateT> - OutputIteratorT - trim_right_copy_if(OutputIteratorT Output, const RangeT & Input, - PredicateT IsSpace); -template<typename SequenceT, typename PredicateT> - SequenceT trim_right_copy_if(const SequenceT & Input, PredicateT IsSpace);
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
-An input range
An unary predicate identifying spaces
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
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::algorithm::trim_right_if — Right trim - parametric.
--template<typename SequenceT, typename PredicateT> - void trim_right_if(SequenceT & Input, PredicateT IsSpace);
- | Copyright © 2002-2004 Pavol Droba | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-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(); -};
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 , 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/destructtry_mutex();-
Effects:
-
- Constructs a try_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::try_read_write_mutex —
The try_read_write_mutex class is a model of the - TryReadWriteMutex concept.
--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(); -};
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 , 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. -
-try_read_write_mutex
construct/copy/destructtry_read_write_mutex(boost::read_write_scheduling_policy count);-
Effects:
-
- Constructs a try_read_write_mutex object.
-
Postconditions:
-
- *this
is in an unlocked state.
-
~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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 * multitoken() ; - typed_value * zero_tokens() ; - std::string name() const; - bool is_composing() const; - unsigned min_tokens() const; - unsigned max_tokens() 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; -};
Class which handles value of a specific type.
- -typed_value
public member functionstyped_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.
-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.
-typed_value * notifier(function1< void, const T & > f) ;-
Specifies a function to be called when the final value is determined.
-typed_value * composing() ;-
Specifies that the value is composing. See the 'is_composing' method for explanation.
-typed_value * multitoken() ;-
Specifies that the value can span multiple tokens.
-typed_value * zero_tokens() ;
std::string name() const;
bool is_composing() const;
unsigned min_tokens() const;
unsigned max_tokens() const;
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.
-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.
-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.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::tz_db_base — Creates a database of time_zones from csv datafile.
-template<typename time_zone_type, typename rule_type> -class tz_db_base { -public: - // types - typedef char charT; - typedef time_zone_type::base_type time_zone_base_type; - typedef time_zone_type::time_duration_type time_duration_type; - typedef time_zone_names_base< charT > time_zone_names; - typedef dst_adjustment_offsets< time_duration_type > dst_adjustment_offsets; - typedef std::basic_string< charT > string_type; - - // construct/copy/destruct - tz_db_base(); - - // public member functions - void load_from_file(const std::string &) ; - bool add_record(const string_type &, - boost::shared_ptr< time_zone_base_type >) ; - boost::shared_ptr< time_zone_base_type > - time_zone_from_region(const string_type &) const; - std::vector< std::string > region_list() const; - - // private member functions - rule_type * parse_rules(const string_type &, const string_type &) const; - week_num get_week_num(int) const; - void split_rule_spec(int &, int &, int &, string_type) const; - bool parse_string(string_type &) ; -};
The csv file containing the zone_specs used by the tz_db_base is intended to be customized by the library user. When customizing this file (or creating your own) the file must follow a specific format.
-This first line is expected to contain column headings and is therefore not processed by the tz_db_base.
-Each record (line) must have eleven fields. Some of those fields can be empty. Every field (even empty ones) must be enclosed in double-quotes. Ex:
-"America/Phoenix" <- string enclosed in quotes - "" <- empty field --
Some fields represent a length of time. The format of these fields must be:
-"{+|-}hh:mm[:ss]" <- length-of-time format --
Where the plus or minus is mandatory and the seconds are optional.
-Since some time zones do not use daylight savings it is not always necessary for every field in a zone_spec to contain a value. All zone_specs must have at least ID and GMT offset. Zones that use daylight savings must have all fields filled except: STD ABBR, STD NAME, DST NAME. You should take note that DST ABBR is mandatory for zones that use daylight savings (see field descriptions for further details).
-******* Fields and their description/details *********
-ID: Contains the identifying string for the zone_spec. Any string will do as long as it's unique. No two ID's can be the same.
-STD ABBR: STD NAME: DST ABBR: DST NAME: These four are all the names and abbreviations used by the time zone being described. While any string will do in these fields, care should be taken. These fields hold the strings that will be used in the output of many of the local_time classes. Ex:
-time_zone nyc = tz_db.time_zone_from_region("America/New_York"); - local_time ny_time(date(2004, Aug, 30), IS_DST, nyc); - cout << ny_time.to_long_string() << endl; - // 2004-Aug-30 00:00:00 Eastern Daylight Time - cout << ny_time.to_short_string() << endl; - // 2004-Aug-30 00:00:00 EDT --
NOTE: The exact format/function names may vary - see local_time documentation for further details.
-GMT offset: This is the number of hours added to utc to get the local time before any daylight savings adjustments are made. Some examples are: America/New_York offset -5 hours, & Africa/Cairo offset +2 hours. The format must follow the length-of-time format described above.
-DST adjustment: The amount of time added to gmt_offset when daylight savings is in effect. The format must follow the length-of-time format described above.
-DST Start Date rule: This is a specially formatted string that describes the day of year in which the transition take place. It holds three fields of it's own, separated by semicolons. The first field indicates the "nth" weekday of the month. The possible values are: 1 (first), 2 (second), 3 (third), 4 (fourth), 5 (fifth), and -1 (last). The second field indicates the day-of-week from 0-6 (Sun=0). The third field indicates the month from 1-12 (Jan=1).
-Examples are: "-1;5;9"="Last Friday of September", "2;1;3"="Second Monday of March"
-Start time: Start time is the number of hours past midnight, on the day of the start transition, the transition takes place. More simply put, the time of day the transition is made (in 24 hours format). The format must follow the length-of-time format described above with the exception that it must always be positive.
-DST End date rule: See DST Start date rule. The difference here is this is the day daylight savings ends (transition to STD).
-End time: Same as Start time.
- -tz_db_base
public member functionsvoid load_from_file(const std::string & pathspec) ;-
May throw data_not_accessible, or bad_field_count exceptions
-bool add_record(const string_type & id, - boost::shared_ptr< time_zone_base_type > tz) ;-
Takes an id string in the form of "America/Phoenix", and a time_zone object for that region. The id string must be a unique name that does not already exist in the database.
-boost::shared_ptr< time_zone_base_type > -time_zone_from_region(const string_type & region) const;-
Returns a time_zone object built from the specs for the given region. If region does not exist a local_time::record_not_found exception will be thrown
-std::vector< std::string > region_list() const;
tz_db_base
private member functionsrule_type * parse_rules(const string_type & sr, const string_type & er) const;
week_num get_week_num(int nth) const;
void split_rule_spec(int & nth, int & d, int & m, string_type rule) const;
bool parse_string(string_type & s) ;-
Take a line from the csv, turn it into a time_zone_type, and add it to the map. Zone_specs in csv file are expected to have eleven fields that describe the time zone. Returns true if zone_spec successfully added to database
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::uk_dst_trait — Alternative dst traits for some parts of the United Kingdom.
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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 -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; - unsigned min_tokens() const; - unsigned max_tokens() const; - bool is_composing() const; - void xparse(boost::any &, const std::vector< std::string > &) const; - bool apply_default(boost::any &) const; - void notify(const boost::any &) const; -};
Class which specifies a simple handling of a value: the value will have string type and only one token is allowed.
- -untyped_value
public member functionsstd::string name() const;
unsigned min_tokens() const;
unsigned max_tokens() const;
bool is_composing() const;
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.
-bool apply_default(boost::any & ) const;-
Does nothing.
-void notify(const boost::any & ) const;-
Does nothing.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::unwrap_recursive_wrapper —
Unwraps the specified argument if given a specialization of
- recursive_wrapper
.
template<typename T> -class unwrap_recursive_wrapper { -public: - // types - typedef unspecified type; -};
type
is equivalent to T::type
if
- T
is a specialization of
- recursive_wrapper
. Otherwise,
- type
is equivalent to T
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::unwrap_reference — Find the type in a reference_wrapper
.
template<typename T> -class unwrap_reference { -public: - // types - typedef unspecified type; -};
- | Copyright © 1999, 2000 Jaakko Järvi Copyright © 2001, 2002 Peter Dimov Copyright © 2002 David Abrahams |
-
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::us_dst_rules — Depricated: Class to calculate dst boundaries for US time zones.
-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() ; -};
us_dst_rules
public static functionstime_is_dst_result -local_is_dst(const date_type & d, const time_duration_type & td) ;-
Determines if the time is really in DST or not. Also checks for invalid and ambiguous. -
-bool is_dst_boundary_day(date_type d) ;
date_type local_dst_start_day(year_type year) ;
date_type local_dst_end_day(year_type year) ;
time_duration_type dst_offset() ;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::us_dst_trait — Specification for daylight savings start rules in US.
-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() ; -};
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.
- -- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::utc_adjustment — Provides a base offset adjustment from utc.
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::value —
--template<typename T> typed_value< T > * value(); -template<typename T> typed_value< T > * value(T * v);
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.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::value_semantic —
--class value_semantic { -public: - // construct/copy/destruct - ~value_semantic(); - - // public member functions - virtual std::string name() const; - virtual unsigned min_tokens() const; - virtual unsigned max_tokens() const; - virtual bool is_composing() 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; -};
Class which specifies how the option's value is to be parsed and converted into C++ types.
- -value_semantic
public member functionsvirtual std::string name() const;-
Returns the name of the option. The name is only meaningful for automatic help message.
-virtual unsigned min_tokens() const;-
The minimum number of tokens for this option that should be present on the command line.
-virtual unsigned max_tokens() const;-
The maximum number of tokens for this option that should be present on the command line.
-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.
-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.
-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.
-virtual void notify(const boost::any & value_store) const;-
Called when final value of an option is determined.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::var_string_to_int — Helper function for parsing varied length strings into integers.
--template<typename int_type, typename charT> - int_type var_string_to_int(std::istreambuf_iterator< charT > & itr, - std::istreambuf_iterator< charT > & stream_end, - unsigned int max_length);
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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() ; -};
Class holding value of option. Contains details about how the value is set and allows to conveniently obtain the value.
- -variable_value
public member functionstemplate<typename T> const T & as() const;-
If stored value if of type T, returns that value. Otherwise, throws boost::bad_any_cast exception.
-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.
-bool empty() const;
bool defaulted() const;-
Returns true if the value was not explicitly given, but has default value.
-const boost::any & value() const;-
Returns the contained value.
-boost::any & value() ;-
Returns the contained value.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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; -};
Concrete variables map which store variables in real map.
-variables_map
construct/copy/destructvariables_map();
variables_map(const abstract_variables_map * next);
variables_map
public member functionsconst 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 functionsconst variable_value & get(const std::string & name) const;-
Implementation of abstract_variables_map::get which does 'find' in *this.
-- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2002, 2003 Eric Friedman, Itay 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.
-Table of Contents
-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:
boost::apply_visitor
.boost::get
.boost::make_recursive_variant
and
- boost::recursive_wrapper
.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:
-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.
-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()(conststd::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") -} -
- | - |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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.
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!
Upon learning of this dilemma, clever individuals may propose the - following scheme hoping to solve the problem: - -
-memcpy
) of the
- storage of the left-hand side to the backup storage.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.
-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.
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: - -
-p
.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:
-
-
backup
.backup
to the
- left-hand side storage.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).
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:
-
-
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
.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.)
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.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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: - -
-Of course, Boost.Any has several advantages over Boost.Variant, - such as: - -
-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.
-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.)
-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.
-- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
The requirements on a bounded type - are as follows:
-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:
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.)variant
is itself
- DefaultConstructible if and only if its first
- bounded type (i.e., T1
) meets the requirements of the
- concept.variant
is itself EqualityComparable
- if and only if every one of its bounded types meets the requirements
- of the concept.variant
is itself LessThanComparable
- if and only if every one of its bounded types meets the requirements
- of the concept.variant
is itself OutputStreamable
- if and only if every one of its bounded types meets the requirements
- of the concept.The requirements on a static
- visitor of a type T
are as follows:
operator()
, unambiguously accepting any value of type
- T
.result_type
. (See
- boost::visitor_ptr
for a
- solution to using functions as visitors.)result_type
is not void
, then
- each operation of the function object must return a value implicitly
- convertible to result_type
.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;
- }
-};
-This header exists simply as a convenience to the user, including
- all of the headers in the boost/variant
directory.
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-
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> &); -}-
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; -}-
namespace boost { - template<typename T> class recursive_wrapper; - template<typename T> class is_recursive_wrapper; - template<typename T> class unwrap_recursive_wrapper; -}-
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 &); -}-
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> &); -}-
namespace boost { - class bad_visit; -}-
namespace boost { - template<typename ResultType> class static_visitor; -}-
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)); -}-
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
[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. -
-Type Traits - 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. -
-- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
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
- streamingv
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 anyvariant
(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) - );
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.
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(constboost::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)> >;
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; -typedefmpl::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 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
”.
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 - { - returnboost::apply_visitor
( calculator(), binary.left ) - +boost::apply_visitor
( calculator(), binary.right ); - } - - int operator()(const binary_op<sub> & binary) const - { - returnboost::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 );
-}
-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
”.
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 & ) const
- {
- return false; // cannot compare different types
- }
-
- template <typename T>
- bool operator()( const T & lhs, const T & rhs ) const
- {
- 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 ) - ) );
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::visit_each — Allow limited exploration of class members.
--template<typename Visitor, typename T> - void visit_each(const Visitor& visitor, const T& t, int );
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)
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.
-- | Copyright © 2001-2004 Douglas Gregor | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::visitor_ptr —
Returns a visitor object that adapts function pointers for - use as a static visitor.
--template<typename R, typename T> visitor_ptr_t<T,R> visitor_ptr(R (*)(T) );
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.)
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::visitor_ptr_t — Adapts a function pointer for use as a static visitor.
-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&); -};
Adapts the function given at construction for use as a
- static visitor
- of type T
with result type R
.
visitor_ptr_t
static visitor interfacesR 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
.
- | Copyright © 2002, 2003 Eric Friedman, Itay Maman | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::week_functor — Functor to iterate a over weeks.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::weeks_duration — Additional duration type that represents a number of n*7 days.
-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 -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
Copyright © 2005 Various Authors
- 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 - ) - -
-Table of Contents
- --Open source isn't just for nerds and researchers. Real world programming challenges, -irrespective of whether they are open or closed source, can benefit enormously from -the thought and experience that has gone into the Boost software libraries. Put simply, -for any given problem for which Boost provides a solution, Boost will strive to provide -the best solution possible. It's up to you to decide whether we've achieved that, but -as these pages will testify, many other developers have found our solutions to be the -best for them.
-Disclaimer: Boost's developers try to ensure that the -information on these pages is correct, but from time to time inadvertent -mistakes are bound to occur: -if you would like an entry in these pages to be removed or corrected please contact -the Boost Moderators.
-Last revised: June 23, 2005 at 11:38:28 GMT |
-- |
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Whether you're a government department, an internet startup, or a specialist consultancy, in-house -developement using the Boost Libraries can significantly shorten your -development cycles.
-
-LiquidNet LiquidNet is Americas number one electronic -marketplace for large block trading, and the 5th fastest growing company -according to Inc Magazine. - -"Boost Libraries most used, in order of importance: shared_ptr, -bind, -boost.python, -lexical_cast, -optional, -any and -tuple - |
-MetOcean Engineers MetOcean Engineers -are a leading consultancy providing oceanographic and meteorological -services in support of coastal and ocean engineering and environmental -protection. Core activities encompass: oceanographic measurements; -metocean monitoring systems; coastal and ocean engineering; environmental -consultancy; data management. - -Boost Libraries currently in use: -boost.any, -boost.assign, -boost.bind, -boost.date_time, -boost.iterators, -boost.lexical_cast, -boost.mpl, -boost.phoenix, -boost.program_options, -boost.ref, -boost.smart_ptr, -boost.spirit, -boost.string_algo, -boost.tribool and -boost.variant - |
-TeraView Ltd TeraView Ltd develop terahertz based systems -for a variety of applications -including spectroscopy and imaging. "We use: -thread, -filesystem, -date_time, -serialization, -smart_ptr, -function, -bind, -iterator, -lexical_cast, -format, -tuple, -any and -optional" - |
-NPC International - -With about 800 restaurants, NPC International -is the world's largest Pizza Hut franchisee. "We make extensive use of boost in our internally developed point of sale, -restaurant management, communications, and accounting systems. -We use the following libraries in approximate order of frequency of use: -bind, -function, -optional, -shared_ptr, -date_time, -thread, -lambda, -type_traits, -mpl, -tuple, -enable_if, -variant, -spirit, -string_algo, -preprocessor, -filesystem, -operator, -iterators and -tokenizer." - |
-Archelon LLC Archelon LLC is a global securities firm -headquartered in Chicago. We actively trade equities, futures and -derivatives in both electronic and floor-based markets. Archelon is -one of the highest volume market makers on EUREX and a leading -U.S. option market maker focusing on the most active securities. "We use: -any, -array, -bind, -date_time, -function, -lexical_cast, -optional, -rational, -regex, -signals, -smart_ptr, -tokenizer, -tuple and -utility." - |
- | Copyright © 2005 Various Authors | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Boost is used in a variety of Open Source Projects, both applications and libraries. -Indeed many Open Source libraries developed around Boost have in the past been judged -of high enough quality to be absorbed -into the main Boost source tree, a process that will no doubt continue into the future. -Others are in highly specialized niche markets, ranging from probability theory to -astronomy, via mass spectroscopy: whatever your field of interest you'll find -something of value in Boost.
-
-Adobe Software Libraries - -The Adobe Software Libraries provide -components for modeling the human interface appearance and behavior -in a software application. The Adobe Software Libraries depend on many -parts of Boost including Any, -Bind, Function, -MPL, Operators, -Range, Static Assertions, -Threads, and Type Traits. - -Currently Boost and the Adobe Software Libraries are in use in around 30 Adobe products. - |
-Lyx Document Editor The Lyx Document Editor -is an advanced open source document processor that encourages an -approach to writing based on the structure of your documents, -not their appearance. LyX produces high quality, professional output, -using LaTeX, an industrial strength typesetting engine. - -Lyx uses many parts of Boost, including Array, -Bind, Regex, -Type Traits, -Function, -and Signals. |
-CGAL CGAL is the Computational Geometry Algorithms Library, - an open source C++ library providing generic components - such as triangulations, convex hulls algorithms, boolean - operations of polygons and many other things. - "We currently use the following Boost libraries : - operators, - iterators, - tuples, - concept check, - mpl, - bind, - optional and - smart pointers." - |
-ALPS ALPS is an open source project to develop codes -for the accurate simulation of quantum lattice models, such as quantum magnets, -electronic systems and Bose-Einstein condensates. The main Boost libraries -used are: -graph, -random, -multiarray, -program_options, -lexical_cast, -serialization, -regex, -tuple, -filesystem, -smart_ptr, -bind, -functional and -type_traits - |
-Open VRML Open VRML is a free cross-platform runtime -for VRML. -The basic OpenVRML distribution includes libraries you can use to add -VRML support to an application, and Lookat, a simple stand-alone VRML browser. - |
-Bayes++ Bayes++ is an open source -library that represents and implements a wide variety of numerical algorithms -for Bayesian Filtering of discrete systems from the -Australian Centre for Field Robotics. -Bayes++ makes particularly heavy use of Boost.Ublas -for matrix and numeric computations. - |
-The C++/Tk Library The C++/Tk Library is an open source -C++ interface to the Tk GUI Library. - |
-GluCat GluCat is a library of template classes -which model the universal Clifford algebras over the real or complex fields, -with arbitrary dimension and arbitrary signature. - |
-OpenMS OpenMS is an open source C++ library -for LC/MS data management, reduction, evaluation, visualization, storage and -sophisticated statistical analyses. It can be used to develop mass -spectrometry related applications. - |
-libpdf++ libpdf++ is an object-oriented -library for generating PDF (portable document format) files. It is designed -in a way that the objects in the document are mapped directly to classes -in the library. - |
-Regina Regina is a suite of mathematical software -for 3-manifold topologists. It focuses upon the study of 3-manifold -triangulations and includes support for normal surfaces and angle structures. - |
-MetaFS MetaFS is a daemon for Linux -(and Linux only) that allows you to access information about your -files (such as MP3 tags or JPEG's EXIF tags) easily and consistently -using extended attributes. It also allows you to perform fast searches -using this information. MetaFS is extensible, so anyone can write plug-ins -to access new types of metadata. - |
-The ASN.1 Tool - -Abstract Syntax Notation One (ASN.1) is a -formal language for abstractly describing messages to be exchanged among an -extensive range of applications involving the Internet, intelligent network, -cellular phones, ground-to-air communications, electronic commerce, secure -electronic services, interactive television, intelligent transportation -systems, Voice Over IP and others. The ASN.1 Tool includes two parts : -an ASN.1 compiler "asnparser" which compiles the Abstract Syntax to c++ files, -and a runtime library which is used to link with the c++ files generated by -asnparser. Based on the works of Open H.323 projects, it is developed for -the needs of H.450 series protocol. - |
-DGD DGD (Depression Glass Debug) -is simple, easy to use C++ ostream extension -created with a goal to produce nice, readable and easy to understand trace logs |
-FEAR FEAR is a language independent -open-source project providing portable support for the creation of -genuine Artificial Intelligence within realistic simulated worlds. |
-XEngine XEngine is a platform- and -rendering-API-independent 3D engine for real-time visualization with -support for programmable graphics pipeline architectures and is implemented in C++. |
-Spheral++ Spheral++ is a numerical tool -for simulating the evolution of a set of fluid or solid materials subject to -hydrodynamic, gravitational, and radiative effects. -Spherical++ uses Boost.Python. |
-C++ XML Objects C++ XML Objects is a framework for persisting -hierarchies of C++ objects to and from XML. |
-HippoDraw HippoDraw provides a -highly interactive data analysis environment. -HippoDraw uses Boost.Python. |
-Orocos The Orocos Robot Control Software Application Framework. |
-ECell - -The E-Cell Project is an international research -project aiming at developing necessary theoretical supports, technologies -and software platforms to allow precise whole cell simulation. |
-VCS Made Easy VCS Made Easy, -or vcsme for short, is an utility whose main -purpose is to simplify the maintenance of file trees managed by a version -control system, such as the well known CVS or Subversion. Simply put, -it automates the process of bringing all these directories to an up-to-date -status with a single and simple command. "The following Boost libraries were used: -Format, -Smart Pointers, -Utility (noncopyable) and -Filesystem." - |
-Monotone Monotone -is a free distributed version control system. It provides - a simple, single-file transactional version store, with fully disconnected - operation and an efficient peer-to-peer synchronization protocol. It - understands history-sensitive merging, lightweight branches, integrated - code review and 3rd party testing. It uses cryptographic version naming - and client-side RSA certificates. It has good internationalization support, - has no external dependencies, runs on linux, solaris, OSX, windows, and - other unixes, and is licensed under the GNU GPL. "The followind Boost libraries were used: -Date-Time, -Filesystem, -Conversion, -Optional, -Random, -Regex, -Smart Pointers, -Static Assertions, -Tokenizer, -Tuple and -Test." - |
-Hydranode Engine Hydranode Engine -is a plugin-driven P2P client engine that relies -heavily on Boost libraries. Hydranode codebase is licenced under GNU -GPL, and is developed mainly by Alo Sarv. Currently in Beta phase, -Hydranode runs on wide range of platforms, including Windows, Linux, -BSD, Mac OS, Solaris etc. "Hydranode Engine and plugins rely heavily on the following Boost -libraries: Bind, Function, Lambda, MultiIndex, Signals, Threads, -SmartPtr, Format, LexicalCast. Other Boost libraries being used -include FileSystem, StringAlgo, DateTime, ProgramOptions, Spirit, -Random, Tokenizer, TypeTraits, Tribool, Tuple and Any. Once Boost 1.33 -is released, I'm also looking forward to using Boost.IOStreams library -in Hydranode. - -All complex data structures in Hydranode are implemented using -MultiIndex containers, which significantly reduced development time -and kept code clean. Format is being used for all text formatting. -Having Threads and FileSystem libraries available made cross-platform -development lot easier in those areas." - |
-Hugin - -With hugin you can assemble a mosiac of -photographs into a complete -immersive panorama, stitch any series of overlapping pictures and much more. |
-Enblend Enblend is a tool for compositing images. -Given a set of images that overlap -in some irregular way, Enblend overlays them in such a way that the seam -between the images is invisible, or at least very difficult to see. |
-GNU Source-highlight GNU Source-highlight, -given a source file, produces a document with -syntax highlighting. The colors and the styles can be specified -(bold, italics, underline) by means of a configuration file, and some -other options can be specified at the command line. The output format -can be HTML, XHTML and ANSI color escape sequences. GNU Source Highlight -is build around Boost.Regex - |
-Luabind Luabind is a library that helps you create -bindings between C++ and lua. It has the ability to expose functions and classes, -written in C++, to lua. It will also supply the functionality to define classes -in lua and let them derive from other lua classes or C++ classes. -Lua classes can override virtual functions from their C++ baseclasses. -It is written towards lua 5.0, and does not work with lua 4. |
-C++/Tcl C++/Tcl is a library that allows the easy -integration of C++ and Tcl. |
-QuantLib - -The QuantLib project provides a comprehensive software -framework for quantitative finance. QuantLib is a free/open-source library -for modeling, trading, and risk management in real-life. -Boost components used include -smart pointers, -iterators, -and the test framework. - |
- | Copyright © 2005 Various Authors | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-Boost has found it's way into many products that are available "off the shelf", -including consumer applications from Adobe, through to business -middleware from SAP.
-
-Adobe Photoshop CS2 Adobe Photoshop CS2 -uses the -Adobe Software Libraries, which in -turn depend upon large parts of Boost. The Adobe Software Libraries are being rolled -out across the Adobe product line to provide cross platform user interface logic. - |
-Adobe Indesign Adobe Indesign offers -best of breed page design: -Indesign and it's asociated SDK depend upon Boost -regex, -functional and others. - |
-SAP NetWeaver SAP NetWeaver -is the technical foundation of mySAP Business Suite solutions, -SAP xApps composite applications, partner solutions, and customer -custom-built applications. Boost.Regex -provides the regular expression -implementation for SAP's -ABAP language. |
-Real Networks, Rhapsody - -The Rhapsody Music Service allows its subscribers to legally -download/transfer/burn over a million songs. The Rhapsody client -software was built with many Boost libraries. "boost.format: Boost.Format is top notch. Using it is a bliss. boost.functional, -boost.function, and boost.bind: These three libraries, -along with smart pointer are the most used in our application. I could not imagine -not having them handy. boost.smart_ptr: Hands down, the most useful, and used library of the lot! boost.date_time: Simple to use, effective, does the job. I love the -flexible input string parsing facilities, and the -human readable ISO output. boost.iterators: Wow. Moving legacy iterating interfaces, or -interfaces that should of been properly designed -as iterators to STL compliant iterators was easy -and painless. The gains in functionality to our -code made by this library are invaluable. boost.regex: When you need it, it works magic. boost.thread: Used to implement the monitor pattern in key areas. boost.preprocessor: Used to implement repetitive unit-test -code generation. The codebase benefited -greatly from the clarity boost.preprocessor -brought." - |
-McAfee, Managed VirusScan 3 McAfee Managed VirusScan, -is an always on, automatic virus protection for desktops -and servers. - More details of the Boost libraries used can be found -here. |
-DataSolid GmbH Germany, CADdy++ Mechanical Design (c) CADdy++ Mechanical Design professional (c) -is a fully parametric 3D CAD -application with unbroken link between 3D -models and 2D drawings. CADdy++ uses the Boost libraries: -any, -tokenizer, -signals, -property_map, -array, -bind, -operators, -tuple, -random. "Many thanks to all the boost developers for their great work and effort -spending into boost." - |
-Dimesion 5, Miner3D - - Data visualization technology enabling advanced data analysis, - visualization, sonification and speech applications for business and science. - - The Miner3D application provides means for interactive visual analysis of - arbitrary tabular data from various data sources. It has a powerful OpenGL-based - visualization engine and an intuitive GUI. This combination helps a human eye - guide the application of statistical tools and spot the patterns that - might otherwise remain hidden. -"We are using following boost libraries: -Boost.Date Time, -Boost.Variant, -Boost.Regex, -Boost.Format, -Boost.String Algoritms, -Boost.Smart Pointers, -Boost.MPL, -Boost.Type Traits, -Boost.Operators, -Boost.Dynamic Bitset, -Boost.EnableIf, -Boost.Timer." - |
-Synergy, mailIntercept mailIntercept from Synergy -is a mail interceptor service for Exchange Server 2000/2003. - -mailIntercept intercepts and interprets the e-mails from a -LAN using Exchange Server and converts the microsoft proprietary -format to MIME and passes them to an SMTP filter and returns the -emails to the Exchange Server as modified by the SMTP filter, -converted back to the microsoft proprietary format and with its -features preserved. - -mailIntercept was built using -boost.mpl, -boost.string_algo, -boost.bind, -boost.phoenix, -boost.spirit, -boost.ptr_container, -boost.serialization, -boost.regex, -boost.iterators, -boost.lambda, -boost.lexical_cast, -boost.operators, -boost.smart_ptr, -boost.tribool and -boost.type_traits - |
-Integrated Research P/L, PROGNOSIS IP Telephony Manager and IP Telephony Express PROGNOSIS is a suite of IP telephony management software products, - specifically designed to address the key challenges of IP telephony - life cycle management, including network-readiness, assessment, - pre-deployment assurance testing, and ongoing Day-2 management of - Cisco CallManager, Cisco Unity, and Cisco AVVID infrastructure. -"The Boost libraries used were: -boost.any, - boost.bind, - boost.function, - boost.lexical_cast, - boost.mpl, - boost.numeric_cast, - boost.ref, - boost.regex, - boost.smart_ptr, - boost.thread, - boost.type_traits." - |
-Kinook Software, Visual Build Professional Visual Build Professional -is a tool that enables developers, -software process engineers, and build specialists to create an -automated, repeatable process for building their software. Visual Build -provides built-in support for Microsoft Visual Studio .NET and 2005, -Visual Basic, Visual C++, Visual J++, SourceSafe, eMbedded Tools, -Borland Delphi, JBuilder, C++Builder, and more. - -The following Boost Libraries were used: -any, -mem_fn, -regex, -smart_ptr, -static_assert - |
-Kinook Software, Ultra Recall Ultra Recall -is a personal information management (PIM) / -knowledge management (KM) application for Microsoft Windows. It helps -you capture, organize, and recall all of your electronic information -across all the applications that you use. - -Used the following Boost libraries: -format, -shared_ptr, -static_assert - |
-Applied Dynamics International, ADvantageDE Applied Dynamics International (ADI) -provides state-of-the art software and -hardware tools to the automotive, aerospace, and defense industries to -design and test embedded control systems. ADI's tools provide advanced capabilities in real-time hardware-in-the-loop -(HIL) simulation, rapid prototyping, and embedded controller software -development. We have been a leading supplier of HIL simulation solutions -since 1957. - -ADvantageDE is the development environment. It allows simulation models to -be easily connected to one another or to hardware components for real-time -simulation. ADvantageDE projects can be created for execution on your PC, -Unix workstation or on our real-time platforms. - -ADvantageVI is the point of control and the graphical user interface for -all of the run-time activities. The run-time architecture includes extensive -features for interacting with, visualizing, and automating simulation and -test activities. - -DasCom provides access to real-time simulation data from most Windows -applications, such as Micrsoft Excel, National Instruments Labview, etc. - -The following Boost Libraries are used: -array, -assign, -bind, -crc, -dynamic_bitset, -enable_if, -file_system, -function, -functional, -iterators, -lambda, -optional, -preprocessor, -ref, -regex, -serialization, -signals, -smart_ptr, -static_assert, -spirit, -string_algo, -tokenizertuple, -utility(noncopyable) and -variant - |
-PeerGuardian PeerGuardian 2 -is Methlabs premier IP blocker for Windows. -With features like support for multiple lists, a list editor, -automatic updates, and blocking all of IPv4 (TCP, UDP, ICMP, etc), -PeerGuardian 2 is the safest and easiest way to protect your privacy on P2P. - -Boost Libraries used include -crc, -bind, -integer, -function, -functional, -smart pointers, -lexical cast, -string algorithms, -random, -format, -utility. |
-DECOMSYS::DESIGNER PRO DECOMSYS::DESIGNER PRO enables the user to design -a highly complex FlexRay communication -system, which is going to be the fundament for tomorrow's -automotive electronics. "Boost Libraries used: -bind, -dynamic_bitset, -format, -function, -iterators, -mpl, -multi_index, -noncopyable, -operators, -preprocessor (nice for generating data for unit tests), -program_options (for the unit test programs), -ref, -regex, -serialization, -signals, -smart_ptr, -spirit, -timer and -variant - -We are also planning to use Andreas Huber's fsm library and iostreams -(together with boost.serialize) once -they are officially released." - |
-Wise Riddles Software, Audiomatic Audiomatic -is a tool used to make system-wide macros and then launch those -macros with a voice command or keyboard shortcut at any time... from any -Windows application. Audiomatic enables you to launch programs, files, or -websites; simulate keystrokes; play sounds; speak text; or even run scripts. -You can do it all with a voice command or keyboard shortcut! -"Libraries Used: -bind, -function, -smart pointers, -date/time, -string, -utility (noncopyable, ref), -regex, -thread, -mpl and -type traits." - |
-Megahard Software Technologies Inc., Rule in Hell Rule in Hell is a -Massively Multiplayer Online Role Playing Game (still in beta). - -The Boost libs used were: -bind, -function, -any, -tuples, -ref, -shared_ptr, -type_traits and -noncopyable. "By far the combination of bind, function, shared_ptr and ref is what we use -most heavily". - |
-Dr. Detlef Meyer-Eltz, TextTransformer - -The TextTransformer -is a Windows IDE for the generation of top down -parsers with included c++ interpreter code for semantic actions. Both -can be executed or debugged immediately on single source files or on -groups of files. Generated parsers can be exported as c++ code -including as well the interpretable code as any arbitrary other code. -Tokens are defined as POSIX regular expressions and rules are defined -in a similar syntax quasi as regular expressions of regular -expressions. The construction of parse trees and their traversal is -supported. "The TextTransformer is essentially based on the boost regex library, -by which the tokens for a parser can be defined. The lexical_cast and -the format library are used for the integrated c++ interpreter. For -the future also an interpreter version of the string_algo part is -planned. The program_options library will be used too to improve the -command line version of the texttransformer." - |
-Redshift Software, The Thot Tool The Thot Tool -is an asset management tool for a group of game developers. -Thot combines assets, both binary and text, with workflow automation -into a unified whole, and was built using Boost -threads, -smart_ptr, -regex, -mpl, -and type_traits. - |
- | Copyright © 2005 Various Authors | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
-If you have an application or library that's using Boost and would like to be -listed here, please post the following information to the -main Boost developer -mailing list:
--Finally, if the subheadings used in the structure of these pages -don't fit your Product/Application/Service please say so: we're -always interested to hear how these pages can be improved or better -structured.
-- | Copyright © 2005 Various Authors | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::wrapping_int — A wrapping integer used to support time durations.
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::wrapping_int2 — A wrapping integer used to wrap around at the top.
-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() ; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::program_options::wvalue —
--template<typename T> typed_value< T, wchar_t > * wvalue(); -template<typename T> typed_value< T, wchar_t > * wvalue(T * v);
- | Copyright © 2002-2004 Vladimir Prus | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::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.
-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. 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 - 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
creationint 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.
- | Copyright © 2001-2003 William E. Kempf | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::year_based_generator — Base class for all generators that take a year and produce a date.
-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; - virtual std::string to_string() const; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::year_functor — Functor to iterate by a year adjusting for leap years.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::year_month_day_base — Allow rapid creation of ymd triples of different types.
-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; -};
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::years_duration — additional duration type that represents a logical year
-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; -};
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
public member functionsint_rep number_of_years() const;
duration_type get_neg_offset(const date_type & d) const;
duration_type get_offset(const date_type & d) const;
bool operator==(const years_type & rhs) const;
bool operator!=(const years_type & rhs) const;
years_type operator+(const years_type & rhs) const;
years_type & operator+=(const years_type & rhs) ;
years_type operator-(const years_type & rhs) const;
years_type & operator-=(const years_type & rhs) ;
years_type operator *(const int_type rhs) const;
years_type & operator *=(const int_type rhs) ;
years_type operator/(const int_type rhs) const;
years_type & operator/=(const int_type rhs) ;
months_type operator+(const months_type & m) const;
months_type operator-(const months_type & m) const;
- | Copyright © 2001-2005 CrystalClear Software, Inc | -
![]() |
-Home | -Libraries | -People | -FAQ | -More | -
boost::date_time::ymd_formatter — Convert ymd to a standard string formatting policies.
-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) ; -};
ymd_formatter
public static functionsstd::basic_string< charT > ymd_to_string(ymd_type ymd) ;-
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
-std::string ymd_to_string(ymd_type ymd) ;-
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
-- | Copyright © 2001-2005 CrystalClear Software, Inc | -