EWL C++ Library Reference Manual
EWL C++ Library Reference Manual
Chapter 1
Introduction
1.1 About the EWL C++ Library Reference Manual........................................................................................................... 53
Chapter 2
The C++ Library
2.1 The EWL C++ Library Overview...................................................................................................................................57
2.2 Definitions.......................................................................................................................................................................57
2.2.2 Character.......................................................................................................................................................... 58
2.2.5 Component....................................................................................................................................................... 59
2.2.12 NTCTS............................................................................................................................................................. 60
2.2.18 Traits................................................................................................................................................................ 61
2.5.1.2 Headers...........................................................................................................................................65
2.5.2.1 Headers...........................................................................................................................................67
2.5.2.2 Linkage...........................................................................................................................................67
2.5.3.3 Headers...........................................................................................................................................68
Chapter 3
3.2.2 is_specialized................................................................................................................................................... 72
3.2.3 min................................................................................................................................................................... 72
3.2.4 max...................................................................................................................................................................73
3.2.5 digits.................................................................................................................................................................73
3.2.6 is_signed...........................................................................................................................................................73
3.2.7 is_integer.......................................................................................................................................................... 73
3.2.8 is_exact.............................................................................................................................................................74
3.2.9 radix................................................................................................................................................................. 74
3.2.10 epsilon.............................................................................................................................................................. 74
3.2.11 round_error.......................................................................................................................................................74
3.2.12 min_exponent...................................................................................................................................................75
3.2.13 min_exponent10...............................................................................................................................................75
3.2.14 max_exponent.................................................................................................................................................. 75
3.2.15 max_exponent10.............................................................................................................................................. 75
3.2.16 has_infinity.......................................................................................................................................................76
3.2.17 has_quiet_NaN.................................................................................................................................................76
3.2.18 has_signaling_NaN.......................................................................................................................................... 76
3.2.19 has_denorm...................................................................................................................................................... 76
3.2.20 has_denorm_loss.............................................................................................................................................. 77
3.2.21 infinity.............................................................................................................................................................. 77
3.2.22 quiet_NaN........................................................................................................................................................ 77
3.2.23 signaling_NaN................................................................................................................................................. 77
3.2.24 denorm_min..................................................................................................................................................... 78
3.2.25 is_iec559.......................................................................................................................................................... 78
3.2.26 is_bounded....................................................................................................................................................... 78
3.2.27 is_modulo.........................................................................................................................................................78
3.2.28 traps.................................................................................................................................................................. 79
3.2.29 tinyness_before................................................................................................................................................ 79
3.2.30 round_style.......................................................................................................................................................79
3.3.1 abort................................................................................................................................................................. 81
3.3.2 atexit.................................................................................................................................................................82
3.3.3 exit....................................................................................................................................................................82
3.4.5.2 Constructor.....................................................................................................................................86
3.4.5.4 destructor........................................................................................................................................86
3.4.5.5 what................................................................................................................................................ 86
3.4.5.7 set_new_handler.............................................................................................................................87
3.5.1.1 Constructors................................................................................................................................... 88
3.5.1.3 operator==......................................................................................................................................88
3.5.1.4 operator!=.......................................................................................................................................88
3.5.1.5 before............................................................................................................................................. 89
3.5.1.6 name............................................................................................................................................... 89
3.5.2.1 Constructors................................................................................................................................... 89
3.5.2.3 what................................................................................................................................................ 90
3.5.3.1 Constructors................................................................................................................................... 90
3.5.3.3 what................................................................................................................................................ 90
3.6.1.1 Constructors................................................................................................................................... 91
3.6.1.3 destructor........................................................................................................................................91
3.6.1.4 what................................................................................................................................................ 92
3.6.2.1.1 Constructors.............................................................................................................. 92
3.6.2.1.3 what...........................................................................................................................92
3.6.2.1.5 set_unexpected..........................................................................................................93
3.6.2.1.6 unexpected................................................................................................................ 93
3.7.2 set_terminate.................................................................................................................................................... 94
3.7.3 terminate...........................................................................................................................................................94
3.7.4 uncaught_exception......................................................................................................................................... 94
Chapter 4
Diagnostics Library
4.1 Exception Classes........................................................................................................................................................... 97
4.2 Assertions........................................................................................................................................................................100
Chapter 5
General Utilities Libraries
5.1 Requirements.................................................................................................................................................................. 103
5.2.1.1 operator!=.......................................................................................................................................106
5.2.1.3 operator<=......................................................................................................................................106
5.2.1.4 operator>=......................................................................................................................................106
5.3 Pairs.................................................................................................................................................................................107
5.3.4 make_pair.........................................................................................................................................................108
5.4.1.3 multiplies........................................................................................................................................109
5.4.2 Comparisons.....................................................................................................................................................110
5.4.2.2 not_equal_to...................................................................................................................................111
5.4.2.3 greater.............................................................................................................................................111
5.4.2.4 less..................................................................................................................................................112
5.4.3.3 logical_not......................................................................................................................................113
5.4.5.4 bind2nd...........................................................................................................................................116
5.4.6.1 pointer_to_unary_function.............................................................................................................116
5.4.6.3 pointer_to_binary_function............................................................................................................116
5.4.7.4 mem_fun_ref_t...............................................................................................................................118
5.4.7.5 mem_fun1_ref_t.............................................................................................................................118
5.4.7.7 const_mem_fun_t...........................................................................................................................119
5.4.7.8 const_mem_fun1_t.........................................................................................................................119
5.5 Memory...........................................................................................................................................................................120
5.5.1.1 address............................................................................................................................................121
5.5.1.4 max_size.........................................................................................................................................121
5.5.2.1 operator==......................................................................................................................................122
5.5.2.2 operator!=.......................................................................................................................................123
5.5.3.4 operator++......................................................................................................................................124
5.5.4.1 get_temporary_buffer.....................................................................................................................125
5.6.3 destructor..........................................................................................................................................................130
5.6.7 get.....................................................................................................................................................................130
5.6.8 release...............................................................................................................................................................131
5.7 C Library.........................................................................................................................................................................132
Chapter 6
Strings Library
6.1 Character traits................................................................................................................................................................ 135
6.1.2.1 assign..............................................................................................................................................136
6.1.2.5 length..............................................................................................................................................137
6.1.2.7 move...............................................................................................................................................138
6.1.2.10 to_char_type...................................................................................................................................138
6.1.2.12 eq_int_type.....................................................................................................................................139
6.1.2.14 eof...................................................................................................................................................139
6.3.2.1 begin...............................................................................................................................................144
6.3.2.4 rend.................................................................................................................................................144
6.3.3.2 length..............................................................................................................................................145
6.3.3.3 max_size.........................................................................................................................................145
6.3.3.8 empty..............................................................................................................................................146
6.3.4.1 operator[]........................................................................................................................................147
6.3.4.2 at.....................................................................................................................................................147
6.3.5.1 operator+=......................................................................................................................................147
6.3.5.3 assign..............................................................................................................................................148
6.3.5.4 insert...............................................................................................................................................149
6.3.6.3 get_allocator...................................................................................................................................151
6.3.7.2 operator==......................................................................................................................................156
6.3.7.3 operator!=.......................................................................................................................................157
6.3.7.6 operator<=......................................................................................................................................158
6.3.7.7 operator>=......................................................................................................................................159
6.3.8.1 operator>>......................................................................................................................................160
6.3.8.2 operator<<......................................................................................................................................160
6.3.8.3 getline.............................................................................................................................................161
Chapter 7
Localization Library
7.1 Supported Locale Names................................................................................................................................................ 165
7.2.3 Errors................................................................................................................................................................168
7.3.2.3 locale::id.........................................................................................................................................172
7.3.2.5 destructor........................................................................................................................................173
7.3.5.1 global..............................................................................................................................................175
7.3.6.1 use_facet.........................................................................................................................................176
7.3.6.2 has_facet.........................................................................................................................................177
7.4.1.1.1 is................................................................................................................................180
7.4.1.1.2 scan_is.......................................................................................................................180
7.4.1.1.6 widen.........................................................................................................................181
7.4.1.2.1 do_is..........................................................................................................................182
7.4.1.2.2 do_scan_is.................................................................................................................182
7.4.1.2.6 do_widen...................................................................................................................183
7.4.1.3.2 Classification.............................................................................................................184
7.4.1.5.1 Constructor................................................................................................................189
7.4.1.5.2 destructor...................................................................................................................189
7.4.1.10.1 noconv.......................................................................................................................195
7.4.1.10.5 EUC...........................................................................................................................196
7.4.1.10.6 UTF-8........................................................................................................................196
7.4.2.2.1 get..............................................................................................................................198
7.4.2.4.1.2 thousands_sep.....................................................................................201
7.4.2.4.1.3 grouping..............................................................................................201
7.4.2.4.1.5 falsename............................................................................................202
7.4.3.1.1 compare.....................................................................................................................206
7.4.3.2.3 Text-Argument:.........................................................................................................209
7.4.3.2.5 Relation:....................................................................................................................209
7.4.3.2.6 Reset:.........................................................................................................................209
7.4.3.2.7 Relationals.................................................................................................................210
7.4.3.2.9 Contraction................................................................................................................211
7.4.3.2.10 Expansion..................................................................................................................211
7.4.4.10.3 abrev_monthname.....................................................................................................229
7.4.4.10.4 monthname................................................................................................................229
7.4.4.10.5 date_time...................................................................................................................229
7.4.4.10.6 am_pm.......................................................................................................................230
7.4.4.10.8 date............................................................................................................................230
7.4.4.10.10 time_zone..................................................................................................................231
7.4.4.10.11 utc_offset...................................................................................................................231
7.4.4.12 Timepunct_byname........................................................................................................................237
7.4.5.4.1.2 thousands_sep.....................................................................................251
7.4.5.4.1.3 grouping..............................................................................................252
7.4.5.4.1.4 curr_symbol........................................................................................252
7.4.5.4.1.5 positive_sign.......................................................................................252
7.4.5.4.1.6 negative_sign......................................................................................252
7.4.5.4.1.8 pos_format..........................................................................................253
7.4.5.4.1.9 neg_format..........................................................................................253
7.4.5.7.1 decimal_point............................................................................................................258
7.4.6.1.1 open...........................................................................................................................262
7.4.6.1.2 get..............................................................................................................................263
Chapter 8
Containers Library
8.1 Container Requirements..................................................................................................................................................271
8.2 Sequences........................................................................................................................................................................274
8.2.1.2 assign..............................................................................................................................................275
8.2.1.4 insert...............................................................................................................................................275
8.2.2.2 assign..............................................................................................................................................277
8.2.2.4 insert...............................................................................................................................................277
8.2.2.6 push_back.......................................................................................................................................278
8.2.2.12 remove............................................................................................................................................279
8.2.2.14 unique.............................................................................................................................................280
8.2.2.15 merge..............................................................................................................................................280
8.2.2.17 sort..................................................................................................................................................280
8.2.5.3 pop..................................................................................................................................................283
8.2.6.1.2 empty.........................................................................................................................283
8.2.6.1.6 pop.............................................................................................................................284
8.2.7.2 assign..............................................................................................................................................285
8.2.7.5 insert...............................................................................................................................................286
8.3.5.2.12 count..........................................................................................................................297
8.3.5.2.17 any.............................................................................................................................299
8.3.5.2.18 none...........................................................................................................................299
Chapter 9
Iterators Library
9.1 Requirements.................................................................................................................................................................. 303
9.3.4.1 advance...........................................................................................................................................306
9.3.4.2 distance...........................................................................................................................................306
9.4.1.4 base.................................................................................................................................................307
9.4.4.3 inserter............................................................................................................................................315
9.5.1.2 destructor........................................................................................................................................316
9.5.2.2 destructor........................................................................................................................................317
9.5.4.3 failed...............................................................................................................................................320
9.6 _EWL_RAW_ITERATORS...........................................................................................................................................321
Chapter 10
Algorithms Library
10.1 Header algorithm............................................................................................................................................................ 323
10.1.1.1 for_each..........................................................................................................................................323
10.1.1.3 find_if.............................................................................................................................................324
10.1.1.7 count...............................................................................................................................................326
10.1.2.14 remove............................................................................................................................................332
10.1.2.18 unique.............................................................................................................................................334
10.1.2.22 rotate...............................................................................................................................................335
10.1.2.23 rotate_copy.....................................................................................................................................335
10.1.2.26 stable_partition...............................................................................................................................336
10.1.3.1 sort..................................................................................................................................................337
10.1.3.4 partial_sort_copy............................................................................................................................338
10.1.3.6 lower_bound...................................................................................................................................339
10.1.3.7 upper_bound...................................................................................................................................339
10.1.3.10 merge..............................................................................................................................................340
10.1.3.14 set_intersection...............................................................................................................................342
10.1.3.17 push_heap.......................................................................................................................................344
10.1.3.22 max.................................................................................................................................................345
10.1.3.23 min_element...................................................................................................................................346
10.1.4.2 qsort................................................................................................................................................348
Chapter 11
Numerics Library
11.1 Numeric type requirements.............................................................................................................................................351
11.2.1.2 Destructor.......................................................................................................................................353
11.2.1.4 operator[]........................................................................................................................................354
11.2.1.5 operator[]........................................................................................................................................354
11.2.2.4 max.................................................................................................................................................357
11.2.2.5 shift.................................................................................................................................................358
11.2.2.6 cshift...............................................................................................................................................358
11.2.2.7 apply...............................................................................................................................................358
11.2.5.2.1 start............................................................................................................................363
11.2.5.2.3 stride..........................................................................................................................363
11.2.7.2.1 start............................................................................................................................365
11.2.7.2.3 stride..........................................................................................................................366
11.3.1.3 partial_sum.....................................................................................................................................371
11.4 C Library.........................................................................................................................................................................372
11.4.2 <cstdlib>...........................................................................................................................................................373
Chapter 12
Complex Class
12.1 Header complex.............................................................................................................................................................. 375
12.3.2.1 real..................................................................................................................................................378
12.3.2.2 imag................................................................................................................................................378
12.3.5.1 real..................................................................................................................................................383
12.3.5.2 imag................................................................................................................................................383
12.3.5.4 arg...................................................................................................................................................383
12.3.5.6 conj.................................................................................................................................................384
12.3.6.4 log...................................................................................................................................................386
12.3.6.5 log10...............................................................................................................................................386
12.3.6.6 pow.................................................................................................................................................387
12.3.6.9 sqrt..................................................................................................................................................387
12.3.6.10 tan...................................................................................................................................................388
12.3.6.11 tanh.................................................................................................................................................388
Chapter 13
Input and Output Library
13.1 Input and Output Library Summary................................................................................................................................389
13.2.1 Definitions........................................................................................................................................................390
Chapter 14
Forward Declarations
14.1 The Streams and String Forward Declarations............................................................................................................... 391
Chapter 15
Iostream Objects
15.1 Header iostream.............................................................................................................................................................. 395
Chapter 16
Iostreams Base Classes
16.1 Header ios....................................................................................................................................................................... 401
16.3.7.2 Destructor.......................................................................................................................................406
16.3.8.5 width...............................................................................................................................................412
16.3.9.1 imbue..............................................................................................................................................413
16.4.2 Destructor.........................................................................................................................................................417
16.4.3.1 tie....................................................................................................................................................418
16.4.3.3 imbue..............................................................................................................................................420
16.4.4.7 eof...................................................................................................................................................427
16.4.4.10 exceptions.......................................................................................................................................431
Chapter 17
Stream Buffers
17.1 Stream buffer requirements.............................................................................................................................................437
17.2.1.1 Destructor.......................................................................................................................................439
17.2.3.3 basic_streambuf::pubseekpos.........................................................................................................442
17.2.4.3 basic_streambuf::sbumpc...............................................................................................................445
17.2.4.5 basic_streambuf::sgetn...................................................................................................................447
17.2.5 Putback.............................................................................................................................................................447
17.2.6.1 basic_streambuf::sputc...................................................................................................................449
17.2.6.2 basic_streambuf::sputn...................................................................................................................450
17.2.7.2 basic_streambuf::gptr.....................................................................................................................451
17.2.7.5 basic_streambuf::setg.....................................................................................................................452
17.2.8.2 basic_streambuf::pptr.....................................................................................................................453
17.2.8.5 basic_streambuf::setp.....................................................................................................................453
17.2.10.3 basic_streambuf::seekpos...............................................................................................................455
17.2.11.2 basic_streambuf::xsgetn.................................................................................................................456
17.2.11.3 basic_streambuf::underflow...........................................................................................................457
17.2.12 Putback.............................................................................................................................................................458
17.2.13.1 basic_streambuf::xsputn.................................................................................................................458
17.2.13.2 basic_streambuf::overflow.............................................................................................................459
Chapter 18
Formatting and Manipulators
18.1 Headers........................................................................................................................................................................... 461
18.2.1.2 Destructor.......................................................................................................................................462
18.2.2.2 Destructor.......................................................................................................................................464
18.2.4.1 basic_istream::gcount.....................................................................................................................470
18.2.4.2 basic_istream::get...........................................................................................................................471
18.2.4.3 basic_istream::getline.....................................................................................................................473
18.2.4.6 basic_istream::read.........................................................................................................................477
18.2.4.8 basic_istream::putback...................................................................................................................479
18.2.4.9 basic_istream::unget.......................................................................................................................481
18.2.5.1 basic_ifstream::ws..........................................................................................................................485
18.2.5.2.1 Destructor..................................................................................................................487
18.3.1.2 Destructor.......................................................................................................................................488
18.3.2.2 Destructor.......................................................................................................................................489
18.3.3.3 basic_ostream::operator<<.............................................................................................................492
18.3.4.5 basic_ostream::flush.......................................................................................................................499
18.3.5.3 basic_ostream::flush.......................................................................................................................503
18.4.2 resetiosflags......................................................................................................................................................505
18.4.3 setiosflags.........................................................................................................................................................505
18.4.5 setfill.................................................................................................................................................................507
18.4.6 setprecision.......................................................................................................................................................507
Chapter 19
String Based Streams
19.1 Header <sstream>........................................................................................................................................................... 511
19.2.2.1 basic_stringbuf::str.........................................................................................................................513
19.3.2.1 basic_istringstream::rdbuf..............................................................................................................517
19.4.2.1 basic_ostringstream::rdbuf.............................................................................................................520
19.5.2.1 basic_stringstream::rdbuf...............................................................................................................524
Chapter 20
File Based Streams
20.1 Header fstream................................................................................................................................................................ 527
20.3.1.1 Constructor.....................................................................................................................................528
20.3.1.2 Destructor.......................................................................................................................................529
20.3.2.2 basic_filebuf::open.........................................................................................................................529
20.3.3.3 basic_filebuf::pbackfail..................................................................................................................532
20.3.3.5 basic_filebuf::seekoff.....................................................................................................................533
20.3.3.7 basic_filebuf::setbuf.......................................................................................................................533
20.3.3.9 basic_filebuf::imbue.......................................................................................................................534
20.4.2.2 basic_ifstream::is_open..................................................................................................................536
20.5.2.1 basic_ofstream::rdbuf.....................................................................................................................540
20.5.2.2 basic_ofstream::is_open.................................................................................................................541
20.6.2.1 basic_fstream::rdbuf.......................................................................................................................544
20.6.2.2 basic_fstream::is_open...................................................................................................................545
Chapter 21
C Library Files
Chapter 22
Strstream
22.1 Header strstream............................................................................................................................................................. 551
22.2.1.2 Destructor.......................................................................................................................................553
22.2.2.2 pcount.............................................................................................................................................554
22.2.2.3 str....................................................................................................................................................554
22.2.3.5 pbackfail.........................................................................................................................................557
22.3.1.2 Destructor.......................................................................................................................................559
22.3.2.2 str....................................................................................................................................................560
22.4.1.2 Destructor.......................................................................................................................................561
22.4.2.2 pcount.............................................................................................................................................562
22.4.2.4 str....................................................................................................................................................563
22.5.2.2 Destructor.......................................................................................................................................564
22.5.3.2 pcount.............................................................................................................................................565
22.5.3.4 str....................................................................................................................................................566
Chapter 23
Bitvector Class Library
23.1 Nested types.................................................................................................................................................................... 569
23.1.1 allocator_type...................................................................................................................................................569
23.1.2 size_type...........................................................................................................................................................569
23.1.3 difference_type.................................................................................................................................................569
23.1.5 reference...........................................................................................................................................................570
23.2.1 Destructor.........................................................................................................................................................573
23.2.2 Assignment.......................................................................................................................................................573
23.3.2 empty................................................................................................................................................................574
23.3.4 max_size...........................................................................................................................................................575
23.3.6 get_allocator.....................................................................................................................................................575
23.6.1 push_back.........................................................................................................................................................577
23.6.2 insert.................................................................................................................................................................578
Chapter 24
EWL_Utility
24.1 Header ewl_utlity............................................................................................................................................................583
24.2.2 remove_volatile................................................................................................................................................584
24.2.5 remove_reference.............................................................................................................................................586
24.2.7 remove_all........................................................................................................................................................586
24.3.1 is_same.............................................................................................................................................................587
24.4.1 is_const.............................................................................................................................................................587
24.7.1 compile_assert..................................................................................................................................................591
24.7.6 compressed_pair...............................................................................................................................................593
Chapter 25
EWL C++ Debug Mode
25.1 Overview of EWL C++ Debug Mode.............................................................................................................................597
25.2.1.2 list...................................................................................................................................................601
25.2.1.3 string...............................................................................................................................................601
25.2.1.4 vector..............................................................................................................................................602
25.2.2 Invariants..........................................................................................................................................................606
Chapter 26
Hash Libraries
26.1 General Hash Issues........................................................................................................................................................609
26.1.2.9 insert...............................................................................................................................................615
26.1.2.10 insert...............................................................................................................................................616
26.2 Hash_set..........................................................................................................................................................................619
Chapter 27
Metrowerks::threads
27.1 Overview of EWL Threads.............................................................................................................................................627
27.3 Threads............................................................................................................................................................................631
27.6 thread_specific_ptr..........................................................................................................................................................640
Chapter 28
EWL std::tr1
28.1 Overview of EWL Implementation of Technical Report 1............................................................................................ 643
28.3.1 reference_wrapper............................................................................................................................................645
28.4.1.1 Constructor.....................................................................................................................................647
28.4.1.2 Destructor.......................................................................................................................................647
28.4.2.1 Member_function...........................................................................................................................649
28.6.1.1 Constructor.....................................................................................................................................650
28.6.1.2 Destructor.......................................................................................................................................650
28.6.2.1 Member_function...........................................................................................................................651
28.7 Template class T0, class T1, ... class T9 class tuple....................................................................................................... 651
28.7.1.1 Constructor.....................................................................................................................................652
28.7.1.2 Destructor.......................................................................................................................................653
28.7.2.1 Member_function...........................................................................................................................654
Chapter 29
Ewlconfig
29.1 C++ Switches, Flags and Defines................................................................................................................................... 665
29.1.3 _Inhibit_Optimize_RB_bit...............................................................................................................................666
29.1.6 _EWL_ARRAY_AUTO_PTR.........................................................................................................................667
29.1.7 _EWL_CFILE_STREAM................................................................................................................................667
29.1.9 _EWL_EXTENDED_BINDERS.....................................................................................................................668
29.1.10 _EWL_EXTENDED_PRECISION_OUTP.....................................................................................................669
29.1.17 _EWL_NO_CONSOLE_IO.............................................................................................................................672
29.1.19 _EWL_NO_EXCEPTIONS.............................................................................................................................672
29.1.21 _EWL_NO_FILE_IO.......................................................................................................................................674
29.1.24 _EWL_NO_REFCOUNT_STRING................................................................................................................674
29.1.28 _EWL_NO_WCHART_C_SUPPORT............................................................................................................675
29.1.32 _EWL_WFILEIO_AVAILABLE....................................................................................................................676
Containers Library discusses container classes: lists, vectors, stacks, and so forth. These
classes provide a C++ program with access to a subset of the most widely used
algorithms and data structures.
Iterators Library discusses iterator classes.
Algorithms Library discusses the algorithms library. This library provides sequence,
sorting, and general numerics algorithms.
The Numerics Library (clause 26) discusses the numerics library. It describes numeric
arrays, generalized numeric algorithms and facilities included from the ISO C library.
Complex Class describes the components for complex number types
Input and Output Library overviews the input and output class libraries.
The Streams and String Forward Declarations discusses the input and output streams
forward declarations.
The Standard Input and Output Stream Library discusses the initialized input and output
objects.
Iostreams Base Classes discusses the iostream_base class.
Stream Buffers discusses the stream buffer classes.
Formatting and Manipulators discusses the formatting and manipulator classes.
String Based Streams discusses the string based stream classes.
File Based Streams discusses the file based stream classes.
C Library Files discusses the namespace C Library functions.
The Strstream Class Library (Annex D) discusses the non standard string stream classes.
Bitvector Class Library discusses the boolean vector class library.
EWL_Utility utilities used for non standard headers.
Overview of EWL C++ Debug Mode describes the Embedded Warrior Library for C++
debug mode facilities.
Hash Libraries describes nonstandard "hash" libraries.
Metrowerks::threads is a reference to threads support in the Embedded Warrior Libraries.
EWL std::tr1 is a reference about items that are proposed for inclusion in the Embedded
Warrior Library
C++ Switches, Flags and Defines is a chapter on the various flags that you can use to
create a customized version of the EWL C++ Library
This section introduces you to the definitions, conventions, terminology, and other
aspects of the EWL C++ library.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Definitions standard C++ terminology
• Additional Definitions additional terminology
• Multi-Thread Safety multi-threaded policy
• Methods of Descriptions standard conventions
• Library-wide Requirements library requirements
2.2 Definitions
This section discusses the meaning of certain terms in the EWL C++ library.
• Arbitrary-Positional Stream
• Character
• Character Sequences
• Comparison Function
• Component
• Default Behavior
• Handler Function
• Iostream Class Templates
• Modifier Function
• Object State
• Narrow-oriented Iostream Classes
• NTCTS
• Observer Function
• Replacement Function
• Required Behavior
• Repositional Stream
• Reserved Function
• Traits
• Wide-oriented Iostream Classes
A stream that can seek to any position within the length of the stream. An arbitrary-
positional stream is also a repositional stream
2.2.2 Character
Any object which, when treated sequentially, can represent text. A character can be
represented by any type that provides the definitions specified.
A class or a type used to represent a character. A character container class shall be a POD
type.
2.2.5 Component
A group of library entities directly related as members, parameters, or return types. For
example, a class and a related non-member template function entity would referred to as
a component.
A non-reserved function that may be called at various points with a program through
supplying a pointer to the function. The definition may be provided by a C++ program.
Templates that take two template arguments: charT and traits. CharT is a character
container class, and traits is a structure which defines additional characteristics and
functions of the character type.
A class member function other than constructors, assignment, or destructor, that alters the
state of an object of the class.
The instantiations of the iostream class templates on the character container class.
Traditional iostream classes are regarded as the narrow-oriented iostream classes.
2.2.12 NTCTS
Null Terminated Character Type Sequences. Traditional char strings are NTCTS.
A stream that can seek only to a position that was previously encountered.
A function, specified as part of the C++ Standard Library, that must be defined by the
implementation. If a C++ program provides a definition for any reserved function, the
results are undefined.
2.2.18 Traits
A class that encapsulates a set of types and functions necessary for template classes and
template functions to manipulate objects of types for which they are instantiated.
The instantiations of the IOSTREAM class templates on the character container class wchar_t
and the default value of the traits parameter.
EWL C++ Library is multi-thread safe provided that the operating system supports
thread-safe system calls.
Library has locks at appropriate places in the code for thread safety. The locks are
implemented as a mutex class -- the implementation of which may differ from platform to
platform.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 61
Additional Definitions
This ensures that the library is MT-Safe internally. For example, if a buffer is shared
between two string class objects (via an internal refcount), then only one string object
will be able to modify the shared buffer at a given time.
Thus the library will work in the presence of multiple threads in the same way as in
single thread provided the user does not share objects between threads or locks between
accesses to objects that are shared.
#include <mutex.h>
std::mutex cout_lock;
int main()
cout_lock.lock();
cout_lock.unlock();
Note that if only one thread is accessing a standard stream then no synchronization is
necessary. For example, one could have one thread handling input from cin, and another
thread handling output to cout, without worrying about mutex objects.
• The length of an NTBS is the number of elements that precede the terminating null
character. An empty NTBS has a length of zero.
• The value of an NTBS is the sequence of values of the elements up to and including
the terminating null character.
• A static NTBS is an NTBS with static storage duration.
To simplify understanding, where objects of certain types are required by the external
specifications of their classes to store data. The declarations for such member objects are
enclosed in a comment that ends with exposition only, as in:
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
64 Freescale Semiconductor, Inc.
Chapter 2 The C++ Library
2.5.1.2 Headers
The components of the EWL C++ Library are declared or defined in various headers.
Table 2-1. EWL C++ Library headers:
C++ Headers C++ Headers
<algorithm> <bitset> <complex> <deque>
<exception> <fstream> <functional> <iomanip>
Unless noted otherwise, the contents of each C style header cname will be the same as that
of the corresponding header name.h. In the EWL C++ Library the declarations and
definitions (except for names which are defined as macros in C) are within namespace
scope of the namespace std.
NOTE
The names defined as macros in C include: assert, errno,
offsetof, setjmp, va_arg, va_end, and va_start.
The Embedded Warrior Library header <cstdlib> includes the functions abort(), atexit(),
and exit().
A description of how a C++ program gains access to the facilities of the C++ Standard
Library.
2.5.2.1 Headers
A header's contents are made available to a translation unit when it contains the
appropriate #include preprocessing directive.
A translation unit shall include a header only outside of any external declaration or
definition, and shall include the header lexically before the first reference to any of the
entities it declares or first defines in that translation unit.
2.5.2.2 Linkage
The Embedded Warrior Library for C++ has external "C++" linkage unless otherwise
specified
Objects and functions defined in the library and required by a C++ program are included
in the program prior to program startup.
Restrictions on C++ programs that use the facilities of the Embedded Warrior Library for
C++.
EWL reserves certain sets of names and function signatures for its implementation.
Names that contain a double underscore (_ _) or begins with an underscore followed by
an upper-case letter is reserved to the EWL library for its use.
Names that begin with an underscore are reserved to the library for use as a name in the
global namespace.
User code can safely use macros that are all uppercase characters and underscores, except
for leading underscores. Library code will either be in namespace std or in namespace
Metrowerks. Implementation details in namespace std will be prefixed by a double
underscore or an underscore followed by an uppercase character. Implementation details
in namespace Metrowerks are nested in a nested namespace, for example:
Metrowerks::details
Each name from the Embedded Warrior Library for C declared with external linkage is
reserved to the implementation for use as a name with extern "C" linkage, both in
namespace std and in the global namespace.
2.5.3.3 Headers
The behavior of any header file with the same name as a Embedded Warrior Library
public or private header is undefined.
Virtual member function signatures defined for a base class in the C++ Standard Library
may be overridden in a derived class defined in the program.
If replacement definition occurs prior to the program startup then replacement functions
are allowed.
A C++ program may provide the definition for any of eight dynamic memory allocation
function signatures declared in header <new>.
Listing: Dynamic Memory Allocators
operator new(size_t)
operator new(size_t, const std::nothrow_t&)
operator new[](size_t)
operator delete(void*)
operator delete[](void*)
The EWL C++ library provides default versions of the following handler functions:
unexpected_handler
terminate_handler
A C++ program may install different handler functions during execution, by supplying a
pointer to a function defined in the program or the library as an argument to:
set_new_handler
set_unexpected
set_terminate
This chapter describes the implicit functions and temporary objects that may be generated
during the execution of some C++ programs. It also contains information about the
headers for those function, objects and defined types.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Types covers predefined types
• Implementation properties covers implementation defined properties
• Start and termination covers functions used for starting and termination of a program
• Dynamic Memory Management covers operators used for dynamic allocation and
release of memory.
• Type identification covers objects and functions used for runtime type identification.
• Exception Handling covers objects and functions used for exception handling and
errors in exception handling.
• Other Runtime Support covers variations of the standard C library support functions.
3.1 Types
The header <cstddef> contains the same types and definitions as the standard C stddef.h
with the changes shown in the following table.
The numeric_limits component provides a C++ program with information about various
properties of the implementation's representation of the fundamental types.
Specializations including floating point and integer types are provided.
• The member is_specialized shall be true for specializations of numeric_limits.
• Members declared static const in the numeric_limits template specializations are
usable as integral constant expressions.
• Non-fundamental standard types, do not have specializations.
All static members shall be provided but they do not need to be used.
3.2.2 is_specialized
The data member for distinguishing specializations. The default value is false.
3.2.3 min
3.2.4 max
The minimum finite value for floating point types with denormalization.
Remarks
The maximum positive normalized value is returned.
3.2.5 digits
Designates the number of non-signed digits that can be represented for integral types. The
number of radix digits in the mantissa for floating point types
3.2.6 is_signed
3.2.7 is_integer
3.2.8 is_exact
Remarks
All integer types are exact, but not all floating point types are exact.
3.2.9 radix
Specifies the base or radix of the exponent of a floating point type or base of an integral
type.
3.2.10 epsilon
3.2.11 round_error
Remarks
Returns the maximum rounding error.
3.2.12 min_exponent
Holds the minimum exponent so that the radix raised to one less than this would be
normalized.
3.2.13 min_exponent10
Stores the minimum negative exponent that 10 raised to that power would be a
normalized floating point type.
3.2.14 max_exponent
The maximum positive integer so that the radix raised to the power one less than this is
representable.
3.2.15 max_exponent10
The maximum positive integer so that the 10 raised to this power is representable.
3.2.16 has_infinity
3.2.17 has_quiet_NaN
3.2.18 has_signaling_NaN
3.2.19 has_denorm
Remarks
The static variable has_denorm equals denorm_present if the type allows denormalized values.
The variable has_denorm equals denorm_absent if the type does not allow denormalized
values. The variable has_denorm equals denorm_indeterminate if the type is indeterminate for
denormalized values.
3.2.20 has_denorm_loss
3.2.21 infinity
Remarks
Returns a positive infinity if available.
3.2.22 quiet_NaN
Remarks
Returns a quiet "Not a Number" if available.
3.2.23 signaling_NaN
Remarks
Returns a signaling "Not a Number" if available.
3.2.24 denorm_min
Remarks
Returns the minimum positive denormalized value.
3.2.25 is_iec559
The values is true if and only if the type adheres to IEC 559 standard
3.2.26 is_bounded
The value is true if the set of values representable by the type is finite.
Remarks
All predefined data types are bounded.
3.2.27 is_modulo
This value is true if the type is modulo. A type is modulo if it is possible to add two
positive numbers and have a result that wraps around to a third number that is less.
Remarks
This value is generally true for unsigned integral types and false for floating point types.
3.2.28 traps
3.2.29 tinyness_before
3.2.30 round_style
Remarks
See Also Floating Point Rounding Styles
An enumerated type in std namespace that is used to determine the characteristics for
rounding floating point numbers.
Table 3-2. Floating Point Rounding Styles
Enumerated Type Value Meaning
round_indeterminate -1 The rounding is indeterminable
round_toward_zero 0 The rounding is toward zero
round_to_nearest 1 Round is to the nearest value
round_toward_infinity 2 The rounding is to infinity
round_toward_neg_infinity 3 The rounding is to negative infinity
The header <cstdlib> has the same functionality as the standard C header stdlib.h in
regards to start and termination functions except for the functions and macros as
described below.
Table 3-6. Start and Termination Differences
Macro Value Meaning
EXIT_FAILURE 1 This macro is used to signify a failed
return
EXIT_SUCCESS 0 This macro is used to signify a
successful return
The return from the main function is ignored on the Macintosh operating system and is
returned using the native event processing method on other operating systems.
3.3.1 abort
abort(void)
Remarks
The program is terminated without executing destructors for objects of automatic or static
storage duration and without calling the functions passed to atexit.
3.3.2 atexit
The atexit function registers functions to be called when exit is called in normal program
termination.
extern "C" int atexit(void (* f)(void))
Remarks
If there is no handler for a thrown exception terminate is called. The registration of at
least 32 functions is allowed.
• Functions registered with atexit are called in reverse order.
• A function registered with atexit before an object of static storage duration will not
be called until the objects's destruction.
• A function registered with atexit after an object of static storage duration is
initialized will be called before the object's destruction.
The atexit() function returns zero if the registration succeeds, non zero if it fails.
3.3.3 exit
exit(int status)
Remarks
The header <new> defines procedures for the management of dynamic allocation and
error reporting of dynamic allocation errors.
This clause covers storage allocation and deallocation functions and error management.
const std::nothrow_t&)throw();
Remarks
The nothrow version of new returns a null pointer on failure. The normal version throws a
bad_alloc exception on error.
Remarks
The default operator new will throw an exception upon failure. The nothrow version will
return NULL upon failure.
Operator delete[] is used in conjunction with operator new[] for array allocations.
void operator delete[]
Placement operators are reserved and may not be overloaded by a C++ program.
The placement delete operators are used in conjunction with the corresponding placement
new operators.
void operator delete (void* ptr, void*) throw();
C++ provides for various objects, functions and types for management of allocation
errors.
3.4.5.2 Constructor
bad_alloc() throw();
bad_alloc(const bad_alloc&) throw();
3.4.5.4 destructor
3.4.5.5 what
The type of a handler function that is called by operator new or operator new[].
3.4.5.7 set_new_handler
Returns zero on the first call and the previous new_handler upon further calls.
The header <typeinfo> defines three types for type identification and type identification
errors.
Class type_info contains functions and operations to obtain information about a type.
3.5.1.1 Constructors
3.5.1.3 operator==
3.5.1.4 operator!=
3.5.1.5 before
Returns true if the this pointer precedes the argument the collation order.
3.5.1.6 name
3.5.2.1 Constructors
3.5.2.3 what
3.5.3.1 Constructors
3.5.3.3 what
The header <exception> defines types and procedures necessary for the handling of
exceptions.
3.6.1.1 Constructors
3.6.1.3 destructor
3.6.1.4 what
3.6.2.1.1 Constructors
3.6.2.1.3 what
3.6.2.1.5 set_unexpected
(unexpected_handler f) throw();
3.6.2.1.6 unexpected
void unexpected();
3.7.2 set_terminate
(terminate_handler f) throw();
3.7.3 terminate
void terminate();
Exception handling may be abandoned by the implementation (for example the default
handler) or may be called directly by the program (uncaught exception) among other
reasons. These errors in the exception handling mechanism are handled using terminate.
3.7.4 uncaught_exception
bool uncaught_exception();
If the second parameter of va_start is declared with a function, array, reference type or
with a type for which there is no parameter, the behavior is undefined
Table 3-8. Header <csetjmp>
setjmp A macro used in C++ Runtime support
jmp_buf A type used in C++ Runtime support
longjmp A function used in C++ Runtime support
NOTE
All signal handlers should have C linkage.
Table 3-11. Header <cstdlib>
getenv A function used in C++ Runtime support
system A function used in C++ Runtime support
This chapter describes objects and facilities used to report error conditions.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Exception Classes
• Assertions
• Error Numbers
The library provides for exception classes for use with logic errors and runtime errors.
Logic errors in theory can be predicted in advance while runtime errors can not. The
header <stdexcept> predefines several types of exceptions for C++ error reporting.
The logic_error class is derived from the Class exception and is used for exceptions that
are detectable before program execution.
Constructors
A derived class of logic error the domain_error object is used for exceptions of domain
errors.
Constructors
A derived class of logic_error the length_error is use to report exceptions when an object
exceeds allowed sizes.
Constructors
A derived class of logic_error an object of out_of_range is used for exceptions for out of
range errors.
Constructors
Derived from the Class exception the runtime_error object is used to report errors
detectable only during runtime.
Constructors
Constructs an object of the class runtime_error. Initializes exception::what to the what_arg
argument
Derived form the runtime_error class, an object of range_error is used for exceptions due to
runtime out of range errors.
Constructors
runtime_error(const string& what_arg);
The overflow_error object is derived from the class runtime_error and is used to report
arithmetical overflow errors.
Constructors
The class underflow_error is derived from the class runtime_error and is used to report the
arithmetical underflow error.
Constructors
4.2 Assertions
The header <cassert> provides for the assert macro and is used the same as the standard
C header assert.h
The header <cerrno> provides macros: EDOM ERANGE and errno to be used for
domain and range errors reported by using the errno facility. The <cerrno> header is used
the same as standard C header errno.h
This clause describes components used by other elements of the Standard C++ library.
These components may also be used by C++ programs.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Requirements
• Utility Components
• Pairs
• Function objects
• Memory
• Template Class Auto_ptr
• C Library
• Date and Time
5.1 Requirements
This section describes the requirements for template arguments, types used to instantiate
templates and storage allocators used as general utilities.
The equality comparison operator is required. The (==) expression has a bool return type
and specifies that for x == y and y == z that x will equal z. In addition the reciprocal is
also true. That is, i f x == y then y equals x. Also i f x == y and y == z then z will be equal
to x.
A copy constructor for the general utilities library has the following requirements:
• If the copy constructor is TYPE(t) then the argument must be an equivalent of TYPE.
• If the copy constructor is TYPE(const t) then the argument must be the equivalent of
const TYPE.
• &T, denotes the address of T.
• &const T, denotes the address of const T.
A default constructor is not necessary. However, some container class members may
specify a default constructor as a default argument. In that case when a default
constructor is used as a default argument there must be a default constructor defined.
The general utilities library requirements include requirements for allocators. Allocators
are objects that contain information about the container. This includes information
concerning pointer types, the type of their difference, the size of objects in this allocation,
also the memory allocation and deallocation information. All of the standard containers
are parameterized in terms of allocators.
This sub-clause contains some basic template functions and classes that are used
throughout the rest of the library.
5.2.1 Operators
The Standard C++ library provides general templatized comparison operators that are
based on operator== and operator<.
5.2.1.1 operator!=
This operator determines if the first argument is not equal to the second argument.
5.2.1.2 operator>
This operator determines if the first argument is less than the second argument.
5.2.1.3 operator<=
This operator determines if the first argument is less than or equal to the second
argument.
5.2.1.4 operator>=
This operator determines if the first argument is greater than or equal to the second
argument.
5.3 Pairs
5.3.1 Constructors
The pair class contains various constructors to fit each pairs needs.
pair();
5.3.2 operator ==
The pair equality operator returns true if each pair argument is equal to the other.
template <class T1, class T2>
The pair less than operator returns true if the second pair argument is less that the first
pair argument.
template <class T1, class T2> bool operator <
5.3.4 make_pair
Remarks
Returns a pair of the two arguments.
Function objects have the operator() defined and used for more effective use of the
library.
When a pointer to a function would normally be passed to an algorithm function the
library is specified to accept an object with operator() defined. The use of function
objects with function templates increases the power and efficiency of the library
Struct Unary_function and Struct Binary_function classes are provided to simplify the
typedef of the argument and result types.
NOTE
In order to manipulate function objects that take one or two
arguments it is required that their function objects provide the
defined types. If the function object takes one argument then
argument_type and result_type are defined. If the function
object takes two arguments then the first_argument_type,
second_argument_type, and result_type must be defined.
The utility library provides function object classes with operator() defined for the
arithmetic operations.
5.4.1.1 plus
Adds the first and the second and returns that sum.
template <class T> struct plus : binary_function<T,T,T>
{
T operator()(const T& x, const T& y) const;
};
Remarks
Returns x plus y.
5.4.1.2 minus
Subtracts the second from the first and returns the difference.
template <class T> struct minus : binary_function<T,T,T> {
};
Remarks
Returns x minus y.
5.4.1.3 multiplies
Multiplies the first times the second and returns the resulting value.
template <class T> struct multiplies : binary_function<T,T,T>
{
T operator()(const T& x, const T& y) const;
};
Remarks
Returns x multiplied by y.
5.4.1.4 divides
Divides the first by the second and returns the resulting value.
template <class T> struct divides : binary_function<T,T,T>
{
T operator()(const T& x, const T& y) const;
};
Remarks
Returns x divided by y.
5.4.1.5 modulus
Determines the modulus of the first by the second argument and returns the result.
template <class T> struct modulus : binary_function<T,T,T>
{
T operator()(const T& x, const T& y) const;
};
Remarks
Returns x modulus y.
5.4.1.6 negate
Remarks
Returns the negative of x.
5.4.2 Comparisons
The utility library provides function object classes with operator() defined for the
comparison operations.
NOTE
For the greater, less, greater_equal and less_equal template
classes specializations for pointers yield a total order.
5.4.2.1 equal_to
Remarks
Returns true if x is equal to y.
5.4.2.2 not_equal_to
Returns true if the first argument is not equal to the second argument.
template <class T> struct not_equal_to :
binary_function<T,T,bool>
{
bool operator()(const T& x, const T& y) const;
};
Remarks
Returns true if x is not equal to y.
5.4.2.3 greater
Returns true if the first argument is greater than the second argument.
template <class T> struct greater : binary_function<T,T,bool>
{
bool operator()(const T& x, const T& y) const;
};
Remarks
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 111
Function objects
5.4.2.4 less
Returns true if the first argument is less than the second argument.
template <class T> struct less : binary_function<T,T,bool>
{
bool operator()(const T& x, const T& y) const;
};
Remarks
Returns true if x is less than y.
5.4.2.5 greater_equal
Returns true if the first argument is greater than or equal to the second argument.
template <class T> struct greater_equal :
binary_function<T,T,bool>
{
bool operator()(const T& x, const T& y) const;
};
Remarks
Returns true if x is greater than or equal to y.
5.4.2.6 less_equal
Returns true if the first argument is less than or equal to the second argument.
template <class T> struct less_equal :
binary_function<T,T,bool> {
bool operator()(const T& x, const T& y) const;
};
Remarks
Returns true if x is less than or equal to y.
The utility library provides function object classes with operator() defined for the logical
operations.
5.4.3.1 logical_and
Returns true if the first and the second argument are true.
template <class T> struct logical_and :
binary_function<T,T,bool> {
bool operator()(const T& x, const T& y) const;
};
Remarks
Returns true if x and y are true.
5.4.3.2 logical_or
Remarks
Returns true if the x or y are true.
5.4.3.3 logical_not
Remarks
Returns true if x is equal to zero.
5.4.4 Negators
The utility library provides negators not1 and not2 that returns the complement of the
unary or binary predicate.
A predicate is an object that takes one or two arguments and returns something
convertible to bool.
5.4.4.1 Unary_negate
In the template class unary_negate the operator() returns the compliment of the predicate
argument.
not1
The template function not1 returns the unary_predicate of the predicate argument.
template <class Predicate>
unary_negate<Predicate>
Remarks
Returns true if pred is not true.
5.4.4.2 binary_negate
In the template class binary_negate the operator() returns the compliment of the predicate
arguments.
not2
The template function not2 returns the binary_predicate of the predicate arguments.
template <class Predicate>
binary_negate<Predicate>
Remarks
5.4.5 Binders
The binders classes, bind1st and bind2nd take a function object and a value and return a
function object constructed out of the function bound to the value.
The binders class bind1st takes a function object and a value and return a function object
constructed out of the function bound to the value.
Remarks
The constructor initializes the operation.
5.4.5.2 bind1st
Remarks
Binds the operation to the first argument type.
The binders class bind1st takes a function object and a value and return a function object
constructed out of the function bound to the value.
Remarks
The constructor initializes the operation.
5.4.5.4 bind2nd
binder2nd<Operation> bind2nd
Remarks
Binds the operation to the second argument type.
Special adaptors for pointers to both unary and binary functions call them to work with
function adaptors.
5.4.6.1 pointer_to_unary_function
pointer_to_unary_function<Arg, Result>
ptr_fun(Result (* f)(Arg));
Remarks
Returns a pointer for a unary function.
5.4.6.3 pointer_to_binary_function
pointer_to_binary_function<Arg1,Arg2,Result
Remarks
Returns a pointer for a binary function.
Adaptors for pointers to members are adaptors that allow you to call member functions
for elements within a collection.
5.4.7.1 mem_fun_t
Remarks
The constructor for mem_fun_t calls the member function that is initialized with using a
given pointer argument and an appropriate additional argument.
5.4.7.2 mem_fun1_t
Remarks
The constructor for mem_fun1_t calls the member function that it is initialized with using a
given a pointer argument and an appropriate additional argument.
5.4.7.3 mem_fun
mem_fun(S (T::*f)());
mem_fun(S (T::*f)(A));
Remarks
The function returns an object through which a function can be called.
5.4.7.4 mem_fun_ref_t
Remarks
The function mem_fun_ref_t calls the member function reference it is initialized with usina
a given a reference argument.
5.4.7.5 mem_fun1_ref_t
Remarks
The constructor for mem_fun1_ref_t calls the member function that it is initialized with a
given a reference argument and an additional argument of the appropriate type.
5.4.7.6 mem_fun_ref
mem_fun_ref(S (T::*f)(A));
mem_fun_ref(S (T::*f)(A));
Remarks
The template function mem_fun_ref returns an object through which X::f can be called
given a reference to an X followed by the argument required for f.
5.4.7.7 const_mem_fun_t
Remarks
Provides a constant member to function object.
The constructor for const_mem_fun_t calls the member function that it is initialized with
using a given pointer argument.
5.4.7.8 const_mem_fun1_t
: publid binary_function<T,A,S>
Remarks
The constructor for const_mem_fun1_t calls the member function that it is initialized with
using a given a pointer argument and an additional argument of the appropriate type.
5.4.7.9 const_mem_fun_ref_t
Remarks
The template functions mem_fun_ref returns an object through which X::f can be called.
The constructor for const_mem_fun_ref_t calls the member function that it is initialized with
using a given a reference argument.
5.4.7.10 const_mem_fun1_ref_t
Remarks
The constructor for const_mem_fun1_ref_t calls the member function it is initialized with
using a given a reference argument and an additional argument of the appropriate type.
The template functions mem_fun_ref returns an object through which X::f can be called
5.5 Memory
The header <memory> includes functions and classes for the allocation and deallocation
of memory.
5.5.1.1 address
Remarks
Returns the address of the allocation.
5.5.1.2 allocate
Remarks
A pointer to the initial element of an array of storage.
Allocate throw a bad_alloc exception if the storage cannot be obtained.
5.5.1.3 deallocate
5.5.1.4 max_size
Remarks
Returns the largest size of memory that may be.
5.5.1.5 construct
Remarks
A pointer to the allocated memory is returned.
5.5.1.6 destroy
5.5.2.1 operator==
Equality operator.
(const allocator<T1>&,
Remarks
Returns true if the arguments are equal.
5.5.2.2 operator!=
Inequality operator.
template <class T1, class T2> bool operator!=
(const allocator<T1>&,
Remarks
Returns true if the arguments are not equal.
NOTE
The formal template parameter OutputIterator is required to
have its operator* return an object for which operator& is
defined and returns a pointer to T, and is also required to satisfy
the requirements of an output iterator.
5.5.3.1 Constructors
raw_storage_iterator(OutputIterator x);
Remarks
5.5.3.2 operator *
A dereference operator.
raw_storage_iterator<OutputIterator,T>&
operator*();
Remarks
The dereference operator return *this.
5.5.3.3 operator=
Remarks
Constructs a value from element at the location to which the iterator points.
A reference to the iterator.
5.5.3.4 operator++
operator++(); // Pre-increment
raw_storage_iterator<OutputIterator,T>
operator++(int); //Post-increment
Remarks
Increments the iterator. The post-increment operator returns the old value of the iterator.
The pre-increment operator returns the updated value.
5.5.4.1 get_temporary_buffer
get_temporary_buffer(ptrdiff_t n);
Remarks
Returns an address for the buffer and its size or zero if unsuccessful.
5.5.4.2 return_temporary_buffer
Remarks
The buffer must have been previously allocated by get_temporary_buffer.
5.5.5.1 uninitialized_copy
An uninitialized copy.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 125
Template Class auto_ptr
template <class InputIterator,
class ForwardIterator>
ForwardIterator uninitialized_copy
Remarks
Returns a ForwardIterator to the result argument.
5.5.5.2 uninitialized_fill
An uninitialized fill.
5.5.5.3 uninitialized_fill_n
void uninitialized_fill_n
The auto_ptr class stores a pointer to an object obtained using new and deletes that object
when it is destroyed. For example when a local allocation goes out of scope.
The template auto_ptr_ref holds a reference to an auto_ptr, and is used by the auto_ptr
conversions. This allows auto_ptr objects to be passed to and returned from functions.
NOTE
An auto_ptr owns the object it holds a pointer to. When
copying an auto_ptr the pointer transfers ownership to the
destination.
If more than one auto_ptr owns the same object at the same time the behavior of the
program is undefined.
See the example of using std::auto_ptr and extension version for arrays in Using Auto_ptr
This extension can be turned on by uncommenting the statement,
in <ewlconfig>. No recompile of the C++ lib is necessary, but do
#define _EWL_ARRAY_AUTO_PTR
rebuild any precompiled headers when making this change.
The functionality provided by the extended std::auto_ptr is very similar to that provided
by the newer Metrowerks::alloc_ptr found in <ewl_utility>.
Listing: Using Auto_ptr
#include <iostream>
#include <memory>
using std::auto_ptr;
using std::_Array;
struct A
};
struct B
: A
};
auto_ptr<B> source();
void sink_b(auto_ptr<B>);
void sink_a(auto_ptr<A>);
auto_ptr<B>
void
sink_b(auto_ptr<B>)
void
sink_a(auto_ptr<A>)
array_source()
void
int main()
auto_ptr<B> b2(b);
b = b2;
auto_ptr<B> b3(source());
auto_ptr<A> a(b);
a = b3;
b3 = source();
sink_b(source());
auto_ptr<A> a2(source());
a2 = source();
b = b2;
b3 = array_source();
array_sink(array_source());
auto_ptr(auto_ptr& a) throw();
5.6.2 operator =
auto_ptr<Y>& a) throw();
auto_ptr& operator=
(auto_ptr& a) throw();
Remarks
Returns the this pointer.
5.6.3 destructor
~auto_ptr() throw();
5.6.5 operator*
Remarks
Returns what the dereferenced pointer *this holds.
5.6.6 operator->(
Remarks
Returns what the pointer *this holds.
5.6.7 get
Remarks
Returns what the pointer *this holds.
5.6.8 release
X* release() throw();
Remarks
Returns what the pointer *this holds.
5.6.9 reset
Conversion functionality for the auto_ptr class for copying and converting.
A conversion constructor.
auto_ptr(auto_ptr_ref<X> r) throw();
Remarks
Returns a reference that holds the this pointer.
Remarks
Returns the pointer held.
5.7 C Library
The EWL C++ memory libraries use the C library memory functions. See the EWL C
Reference for <stdlib.h> functions calloc, malloc, free, realloc for more information.
The header <ctime> has the same contents as the Standard C library header <time.h> but
within namespace std.
This chapter is a reference guide to the ANSI/ISO String class that describes components
for manipulating sequences of characters, where characters may be of type char, wchar_t,
or of a type defined in a C++ program.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Character traits defines types and facilities for character manipulations
• String Classes lists string and character structures and classes
• Class Basic_string defines facilities for character sequence manipulations.
• Null Terminated Sequence Utilities lists facilities for Null terminated character
sequence strings.
This section defines a class template char_traits<charT> and two specializations for char
and wchar_t types.
These types are required by string and stream classes and are passed to these classes as
formal parameters charT and traits.
The topics in this section are:
• Character Trait Definitions
• Character Trait Requirements
• Character Trait Type Definitions
• struct char_traits<T>
6.1.1.1 character
Any object when treated sequentially can represent text. This term is not restricted to just
char and wchar_t types
6.1.1.3 traits
A class that defines types and functions necessary for handling characteristics.
6.1.1.4 NTCTS
A null character termination string is a character sequence that proceeds the null
character value charT(0).
6.1.2.1 assign
6.1.2.2 eq
static bool eq
(const char_type&, const char_type&);
6.1.2.3 lt
6.1.2.4 compare
6.1.2.5 length
(const char_type*);
6.1.2.6 find
6.1.2.7 move
Used to move one NTCTS to another even if the receiver contains the sting already.
static char_type* move
6.1.2.8 copy
Used for copying a NTCTS that does not contain the NTCTS already.
static char_type* copy
6.1.2.9 not_eof
(const int_type&);
6.1.2.10 to_char_type
(const int_type&);
6.1.2.11 to_int_type
(const char_type&);
6.1.2.12 eq_int_type
6.1.2.13 get_state
(pos_type pos);
6.1.2.14 eof
Used to return end of file. The value returned from eof() can be used to test against the
return value of basic_istream functions such as get() to determine when another character
can not be returned. It is also used to mean "not a character" on input to various functions
such as basic_ostream::overflow.
There are several types defined in the char_traits structure for both wide and conventional
char types.
The template structure is overloaded for both the wchar_t type struct char_traits<wchar_t>.
This specialization is used for string and stream usage.
NOTE
The assign, eq and lt are the same as the =, == and < operators.
The header <string> define string and trait classes used to manipulate character and wide
character like template arguments.
The class basic_string is used to store and manipulate a sequence of character like types
of varying length known as strings.
The iterators used by basic_string are random iterators and as such qualifies as a
reversible container.
NOTE
In general, the string size can be constrained by memory
restrictions.
The topics in this section include:
• Constructors and Assignments
• Iterator Support
• Capacity
• Element Access
• Modifiers
• String Operations
• Non-Member Functions and Operators
• Inserters and extractors
The class basic_string can have either of two implementations:
• Refcounted.
• Non-refcounted.
The interface and functionality are identical with both implementations. The only
difference is performance. Which performs best is dependent upon usage patterns in each
application.
The refcounted implementation ships as the default.
NOTE
To enable the non-refcounted implementation un-comment
#define _EWL_NO_REFCOUNT_STRING in <ewlconfig>. The C++ library
and precompiled headers must be rebuilt after making this
change.
6.3.1.1 Constructors
The various basic_string constructors construct a string object for character sequence
manipulations. All constructors include an Allocator argument that is used for memory
allocation.
explicit basic_string
(const Allocator& a = Allocator());
This default constructor, constructs an empty string. A zero sized string that may be
copied to is created.
basic_string
(const basic_string& str,
size_type pos = 0,
size_type n = npos,
const Allocator& a = Allocator());
This constructor takes a string class argument and creates a copy of that string, with size
of the length of that string and a capacity at least as large as that string.
An exception is thrown upon failure
basic_string
(const charT* s,
size_type n,
const Allocator& a = Allocator());
This constructor takes a const char array argument and creates a copy of that array with
the size limited to the size_type argument.
The charT* argument shall not be a null pointer
An exception is thrown upon failure
basic_string
(const charT* s,
const Allocator& a = Allocator());
This constructor takes an const char array argument. The size is determined by the size of
the char array.
Th e charT* argument shall not be a null pointer
basic_string
(size_type n,
charT c,
const Allocator& a = Allocator());
This constructor creates a string of size_type n size repeating charT c as the filler.
template<class InputIterator>
basic_string
(InputIterator begin,
InputIterator end,
const Allocator& a = Allocator());
This iterator string takes InputIterator arguments and creates a string with its first position
starts with begin and its ending position is end. Size is the distance between beginning and
end.
6.3.1.2 Destructor
~basic_string ();
Assigns the input string, char array or char type to the current string.
If *this and str are the same object has it has no effect.
Remarks
Both of the overloaded functions construct a string object from the input s, and append it
to the current string.
The assignment operator returns the this pointer.
6.3.2.1 begin
6.3.2.2 end
6.3.2.3 rbegin
6.3.2.4 rend
6.3.3 Capacity
6.3.3.1 size
6.3.3.2 length
6.3.3.3 max_size
6.3.3.4 resize
Remarks
If the size of the string is longer than size_type n, it shortens the string to n, if the size of
the string is shorter than n it appends the string to size n with charT c or charT() if no filler
is specified.
6.3.3.5 capacity
6.3.3.6 reserve
A directive that indicates a planned change is memory size to allow for better memory
management.
6.3.3.7 clear
void clear();
6.3.3.8 empty
Remarks
Returns true if the size is equal to zero, otherwise false.
6.3.4.1 operator[]
6.3.4.2 at
6.3.5 Modifiers
6.3.5.1 operator+=
6.3.5.2 append
basic_string& append(
template<class InputIterator>
6.3.5.3 assign
Assigns a string, Null Terminated Character Type Sequence or char type to the string.
basic_string& assign(const basic_string&);
basic_string& assign
template<class InputIterator>
Remarks
If there is a size argument whichever is smaller the string size or argument value will be
assigned.
6.3.5.4 insert
Inserts a string, Null Terminated Character Type Sequence or char type into the string.
basic_string& insert
basic_string& insert
basic_string& insert
basic_string& insert
template<class InputIterator>
void insert
InputIterator last);
Remarks
May throw an exception.
6.3.5.5 erase
Remarks
May throw an exception.
6.3.5.6 replace
Replaces the string with a string, Null Terminated Character Type Sequence or char type.
basic_string& replace
template<class InputIterator>
basic_string& replace
Remarks
May throw an exception,
6.3.5.7 copy
Copies a Null Terminated Character Type Sequence to a string up to the size designated.
size_type copy(charT* s, size_type n,
Remarks
The function copy does not pad the string with Null characters.
6.3.5.8 swap
void swap(basic_string<charT,traits,Allocator>&);
6.3.6.1 c_str
6.3.6.2 data
6.3.6.3 get_allocator
6.3.6.4 find
Finds a string, Null Terminated Character Type Sequence or char type in a string starting
from the beginning.
size_type find
size_type find
Remarks
The found position or npos if not found.
6.3.6.5 rfind
Finds a string, Null Terminated Character Type Sequence or char type in a string testing
backwards from the end.
size_type rfind
size_type rfind
size_type rfind
Remarks
The found position or npos if not found.
6.3.6.6 find_first_of
Finds the first position of one of the elements in the function's argument starting from the
beginning.
size_type find_first_of
size_type find_first_of
size_type find_first_of
Remarks
The found position or npos if not found.
6.3.6.7 find_last_of
Finds the last position of one of the elements in the function's argument starting from the
beginning.
size_type find_last_of
size_type find_last_of
size_type find_last_of
Remarks
The found position or npos if not found is returned.
6.3.6.8 find_first_not_of
Finds the first position that is not one of the elements in the function's argument starting
from the beginning.
size_type find_first_not_of
size_type find_first_not_of
size_type find_first_not_of
Remarks
The found position or npos if not found.
6.3.6.9 find_last_not_of
Finds the last position that is not one of the elements in the function's argument starting
from the beginning.
size_type find_last_not_of
size_type find_last_not_of
size_type find_last_not_of
Remarks
The found position or npos if not found.
6.3.6.10 substr
Returns a string if possible from beginning at the first arguments position to the last
position.
basic_string substr
Remarks
May throw an exception,
6.3.6.11 compare
int compare(
int compare
int compare
Return
Less than zero if the string is smaller than the argument lexicographically, zero if the
string is the same size as the argument lexicographically and greater than zero if the
string is larger than the argument lexicographically.
Non-member functions.
6.3.7.1 operator+
basic_string<charT,traits,Allocator>operator+
basic_string<charT,traits,Allocator> operator+
basic_string<charT,traits,Allocator> operator+
<charT,traits,Allocator>& rhs);
basic_string<charT,traits,Allocator> operator+
basic_string<charT,traits,Allocator> operator+
Remarks
The combined strings are returned.
6.3.7.2 operator==
bool operator==
bool operator==
<charT,traits,Allocator>& rhs);
bool operator==
Return
True if the strings match otherwise false.
6.3.7.3 operator!=
bool operator!=
bool operator!=
<charT,traits,Allocator>& rhs);
bool operator!=
Remarks
True if the strings do not match otherwise false.
6.3.7.4 operator<
bool operator<
bool operator<
<charT,traits,Allocator>& rhs);
bool operator<
Remarks
Returns true if the first argument is lexicographically less than the second argument
otherwise false.
6.3.7.5 operator>
bool operator>
bool operator>
<charT,traits,Allocator>& rhs);
bool operator>
Remarks
Returns True if the first argument is lexicographically greater than the second argument
otherwise false.
6.3.7.6 operator<=
bool operator<=
bool operator<=
bool operator<=
Remarks
Returns true if the first argument is lexicographically less than or equal to the second
argument otherwise false.
6.3.7.7 operator>=
bool operator>=
bool operator>=
bool operator>=
Remarks
Returns true if the first argument is lexicographically greater than or equal to the second
argument otherwise false.
6.3.7.8 swap
This non member swap exchanges the first and second arguments.
template <class charT, class traits, class Allocator>
void swap
(basic_string<charT,traits,Allocator>& lhs,
6.3.8.1 operator>>
basic_istream<charT,traits>& operator>>
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str);
Remarks
Characters are extracted and appended until n characters are stored or end-of-file occurs
on the input sequence;
6.3.8.2 operator<<
6.3.8.3 getline
basic_istream<charT,traits>& getline
(basic_istream<charT,traits>& is,
basic_istream<charT,traits>& getline
(basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str)
Remarks
Extracts characters from a stream and appends them to the string until the end-of-file
occurs on the input sequence (in which case, the getline function calls setstate(eofbit) or
the delimiter is encountered in which case, the delimiter is extracted but not appended.
If the function extracts no characters, it calls setstate(failbit) in which case it may throw
an exception.
The standard requires C++ versions of the standard libraries for use with characters and
Null Terminated Character Type Sequences.
The standard provides for namespace and wide character type for Null Terminated
Character Type Sequence functionality.
Table 6-3. String support testing
<cstring.h> <wchar.h> <cstring.h> <wchar.h>
memchr wmemchr strerror
memcmp wmemcmp strlen wcslen
memcpy wmemcpy strncat wcsncat
memmove wmemmove strncmp wcsncmp
memset wmemset strncpy wcsncpy
strcat wcscat strpbrk wcspbrk
strchr wcschr strrchr wcsrchr
strcmp wcscmp strspn wcsspn
strcoll wcscoll strstr wcsstr
strcpy wcscpy strtok wcstok
strcspn wcscspn strxfrm wcsxfrm
The standard provides for namespace and wide character support for manipulation and
conversions of input and output and character and character sequences.
Table 6-4. Additional <wchar.h> and <stdlib.h> support
wchar.h wchar.h wchar.h <cstdlib.h>
btowc mbrtowc wcrtomb atol
fgetwc mbsinit wcscoll atof
fgetws mbsrtowcs wcsftime atoi
fputwc putwc wcstod mblen
fputws putwchar wcstol mbstowcs
fwide swscanf wcsrtombs mbtowc
fwprintf swprintf wcstoul strtod
fwscanf ungetwc wctob strtol
getwc vfwprintf wprintf strtoul
getwchar vwprintf wscanf wctomb
mbrlen vswprintf wcstombs
This chapter describes components that the C++ library that may use for porting to
different cultures.
Much of named locales is implementation defined behavior and is not portable between
vendors. This document specifies the behavior of EWL C++. Other vendors may not
provide this functionality, or may provide it in a different manner.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Supported Locale Names
• Strings and Characters in Locale Data Files
• Locales
• Standard Locale Categories
• C Library Locales
EWL C++ predefines only two names: " C" and "".
However, other names sent to the locale constructor are interpreted as file names
containing data to create a named locale. So localizing your program is as easy as
creating a data file specifying the desired behavior. The format for this data file is
outlined below for each different facet.
A locale is a collection of facets. And a facet is a class that provides a certain behavior.
The " C" locale contains the following facets:
• ctype<char> & ctype<wchar_t>
• codecvt<char, char, mbstate_t> & codecvt<wchar_t, char, mbstate_t>
• num_get<char> & num_get<wchar_t>
A named locale replaces many of these facets with " _byname" versions, whose behavior can
vary based on the name passed.
• ctype_byname<char> & ctype_byname<wchar_t>
• codecvt_byname<char, char, mbstate_t> & codecvt_byname<wchar_t, char, mbstate_t>
• numpunct_byname<char> & numpunct_byname<wchar_t>
• collate_byname<char> & collate_byname<wchar_t>
• time_get_byname<char> & time_get_byname<wchar_t>
• time_put_byname<char> & time_put_byname<wchar_t>
• moneypunct_byname<char, bool> & moneypunct_byname<wchar_t, bool>
• messages_byname<char> & messages_byname<wchar_t>
The behavior of each of these " _byname" facets can be specified with a data file. A single
data file can contain data for all of the byname facets. That way, when you code:
locale myloc("MyLocale");
then the file " MyLocale" will be used for each " _byname" facet in myloc.
NOTE
Unnamed namespaces are displayed using a compiler generated
unique name that has the form: __unnamed_<filename> where
<filename> is the source file name of the main translation unit
that contains the unnamed namespace.
thousands_sep = ','
Both of the above statements set thousands_sep to a comma. Quotes might be necessary
to disambiguate the intended character from ordinary whitespace. For example, to set the
thousands_sep to a space character, quotes must be used:
The whitespace appearing before and after the equal sign is not necessary and
insignificant.
The usual C escape sequences are recognized. For example, to set the thousands_sep to the
single quote character, an escape sequence must be used:
thousands_sep = \'
The octal character may have from 1 to 3 octal digits (digits must be in the range [0, 7].
The parser will read as many digits as it can to interpret a valid octal number. For
example:
\18
When reading narrow data this is the following sequence of 4 char's: '\1' '2' '3' '4'
The '\x01' is read as one character, but the following '2' is not included because a 8 bit
char can only hold 2 hex digits.
When reading wide data the above example parses to the following two wchar_t's:
L'\x123' L'4'
The '\x0123' is read as one wchar_t, but the following '4' is not included because a 16 bit
wchar_t can only hold 4 hex digits.
7.2.3 Errors
If a character is expected, but an end of file occurs, then failbit is set. If a character is
started with a single quote, and end of file occurs before the character within the quotes
can be read, or if a closing quote is not found directly after the character, then failbit will
be set. Depending on the context of when the character is being read, setting failbit may
or may not cause a runtime error to be thrown.
Strings can be quoted or not (using "). If the string contains white space, then it must be
quoted. For example:
Hi there!
This would be parsed as two strings: "Hi" and "there!". But the following is one string:
"Hi there!"
If a string begins with quotes, but does not end with a quote (before end of file), then
failbit will be set. This may nor may not cause a runtime error to be thrown (depending
on the context).
Any of the escape sequences described under character syntax are allowed within strings.
But within strings, single quotes do not delimit characters. Instead single quotes are just
another character in the string. Note that you can use \" to place the string quote character
within a string.
7.3 Locales
The header <locale> defines classes used to contain and manipulate information for a
locale.
• Class locale
• Locale Types
• Locale Members
• Locale Operators
• Locale Static Members
• Locale Globals
• Convenience Interfaces
• Character Classification
• Character Conversions
The class locale contains a set of facets for locale implementation. These facets are as if
they were and index and an interface at the same time.
Two locale constructors can result in a new locale whose name is a combination of the
names of two other locales:
If other has a name (and if one has a name in the case of the second constructor), then the
resulting locale's name is composed from the two locales' names. A combined name
locale has the format:
collate_name/ctype_name/monetary_name/numeric_name/ time_name/messages_name
Each name is the name of a locale from which that category of facets was copied.
The locale loc is created from two locales: other and one. The facets in the categories
collate and numeric are taken from one. The rest of the facets are taken from other. The
name of the resulting locale is:
one/other/other/one/other/other
The locale loc2 is created from the "C" locale and from loc (which already has a
combined name). It takes only the monetary and collate facets from loc, and the rest from
"C":
one/C/other/C/C/C
Using this format, two locales can be compared by name, and if their names are equal,
then they have the same facets.
Listing: Locale example usage:
#include <locale>
#include <iostream>
int main()
using std::locale;
locale::collate | locale::numeric);
locale::collate);
7.3.2.1 locale::Category
7.3.2.2 locale::facet
The class facet is the base class for locale feature sets.
Listing: class locale:: facet synopsis
namespace std {
class locale::facet {
protected:
virtual ~facet();
private:
7.3.2.3 locale::id
The class locale::id is used for an index for locale facet identification.
public:
id();
private:
7.3.2.4 Constructors
Remarks
std::locale a_locale(""); is an example use of the constructor: explicit locale(const char*
std_name);. The "" locale will attempt to read the environment variable
EWL_DEFAULT_LOCALE and create a locale with the associated string. If
getenv("EWL_DEFAULT_LOCALE") returns null, then "C" is used. There is no data file associated
with the "C" locale. The "C" locale is coded directly into EWL C++.
7.3.2.5 destructor
~locale() throw();
7.3.3.1 combine
Creates a copy of the locale except for the type Facet of the argument.
Remarks
The newly created locale is returned.
7.3.3.2 name
Remarks
Returns the name of the locale or "*" if there is none.
7.3.4.1 operator ==
Remarks
The equality operator returns true if both arguments are the same locale.
7.3.4.2 operator !=
Remarks
The non-equality operator returns true if the locales are not the same.
7.3.4.3 operator ()
bool operator()(
const;
Remarks
Returns true if the first argument is less than the second argument for ordering.
7.3.5.1 global
Remarks
Global returns the previous locale.
7.3.5.2 classic
Remarks
This function returns the "C" locale.
7.3.6.1 use_facet
Remarks
Throws a bad_cast exception if has_facet is false.
The function returns a facet reference to corresponding to its argument.
7.3.6.2 has_facet
Remarks
If a facet requested is present has_facet returns true.
In the character classification functions true is returned if the function evaluates to true.
7.3.9.1 toupper
Remarks
Returns the upper case character.
7.3.9.2 tolower
Remarks
Returns the lower case character.
The standard provides for various locale categories for providing formatting and
manipulation of data and streams.
public:
enum mask
alpha = 0x0001,
blank = 0x0002,
cntrl = 0x0004,
digit = 0x0008,
graph = 0x0010,
lower = 0x0020,
print = 0x0040,
punct = 0x0080,
space = 0x0100,
upper = 0x0200,
xdigit = 0x0400,
};
};
7.4.1.1.1 is
const charT* is
(const charT* low, const charT* high,
mask* vec) const;
Fills between the low and high with the mask argument.
Returns the second argument.
7.4.1.1.2 scan_is
Remarks
Returns a pointer to the first character in the range that matches the mask, or the high
argument if there is no match.
7.4.1.1.3 scan_not
Remarks
Returns a pointer to the first character in the range that does not match the mask, or the
high argument if all characters match
7.4.1.1.4 toupper
Remarks
Returns the converted char if it exists.
7.4.1.1.5 tolower
Remarks
Returns the converted char if it exists.
7.4.1.1.6 widen
Remarks
The converted charT is returned.
7.4.1.1.7 narrow
Remarks
The converted char is returned.
7.4.1.2.1 do_is
7.4.1.2.2 do_scan_is
7.4.1.2.3 do_scan_not
7.4.1.2.4 do_toupper
7.4.1.2.5 do_tolower
7.4.1.2.6 do_widen
7.4.1.2.7 do_narrow
• character classification
• conversion to upper/lower case
• conversion to/from char
ctype_byname<char> ct("en_US");
// looks for the file "en_US"
If the file "en_US" exists, has ctype data in it, and there are no syntax errors in the data,
then ct will behave as dictated by that data. If the file exists, but does not have ctype data
in it, then the facet will behave as if it were constructed with "C". If the file has ctype data
in it, but there is a syntax error in the data, or if the file does not exist, then a
std::runtime_error is thrown.
$ctype_narrow
$ctype_wide
7.4.1.3.2 Classification
The classification table is created with one or more entries of the form:
ctype[character1 - character2] =
ctype_classification |
ctype_classification | ...
ctype[character] = ctype_classification |
ctype_classification | ...
where character, character1 and character2 are characters represented according to the
rules for Strings and Characters in Locale Data Files. The characters may appear as
normal characters:
ctype[a - z]
ctype['a' - 'z']
ctype['\101']
ctype['\x41']
ctype['\u41']
The usual escape sequences are also recognized: \n, \t, \a, \\, \' and so on.
On the right hand side of the equal sign, ctype_classification is one of:
• alpha
• blank
• cntrl
• digit
• graph
• lower
• print
• punct
• space
• upper
• xdigit
An | can be used to assign a character, or range of characters, more than one
classification. These keywords correspond to the names of the enum ctype_base::mask,
except that alnum is not present. To get alnum simply specifiy "alpha | digit". The
keyword blank is introduced, motivated by C99's isblank function.
Each of these keywords represent one bit in the ctype_base::mask. Thus for each entry into
the ctype table, one must specify all attributes that apply. For example, in the "C" locale
a-z are represented as:
ctype['a' - 'z'] =
Case transformation is usually handled by a table that maps each character to itself,
except for those characters being transformed - which are mapped to their transformed
counterpart. For example, a lower case map might look like:
lower['a'] == 'a'
lower['A'] == 'a'
This is represented in the ctype data as two tables: lower and upper. You can start a map
by first specifying that all characters map to themselves:
You can then override a subrange in this table to specify that 'A' - 'Z' maps to 'a' - 'z':
These two statements have completely specified the lower case mapping for an 8 bit char.
The upper case table is similar. For example, here is the specification for upper case
mapping of a 16 bit wchar_t in the "C" locale:
Below is the complete "C" locale specification for both ctype_byname<char> and
ctype_byname<wchar_t>. Note that a "C" data file does not actually exist. But if you
provided a locale data file with this information in it, then the behavior would be the
same as the "C" locale.
Listing: Example of "C" Locale
$ctype_narrow
ctype['\x00' - '\x08'] = cntrl
ctype['\x7F'] = cntrl
$ctype_wide
ctype['\x7F'] = cntrl
The class range_map works much like the tables in ctype<char> except that they are sparse
tables. This avoids having tables of length 0xFFFF. These tables map the first template
parameter into the second.
Listing: The range_map interface
template <class T, class U>
class range_map
public:
void insert(const T& x1, const T& x2, const U& y1, const U& y2);
void clear();
};
When constructed, the range_map implicitly holds a map of all T that map to U(). Use of the
insert methods allows exceptions to that default mapping. For example, the first insert
method maps the rang e [x1 - x2] into [y1 - y2]. The second insert method maps the x-
range into a constant: y1. And the third insert method maps the single T(x1) into U(y1).
The method clear() brings the range_map back to the default setting: all T map into U().
A class derived from ctype<wchar_t> can fill __table_,__lower_map_ and __upper_map_ as it
sees fit, and allow the base class to query these tables. For an example see
ctype_byname<wchar_t>.
7.4.1.5.1 Constructor
explicit ctype
(const mask* tbl = 0, bool del = false,
size_t refs = 0);
7.4.1.5.2 destructor
~ctype();
7.4.1.6.1 classic_table
Remarks
Returns to a table that represents the classification in a "C" locale.
A class used for converting one character encoded types to another. For example, from
wide character to multibyte character sets.
7.4.1.8.1.1 out
result out(
stateT& state,const internT* from,
const internT* from_end, const internT*&
from_next, externT* to, externT* to_limit,
externT*& to_next) const;
7.4.1.8.1.2 unshift
7.4.1.8.1.3 in
7.4.1.8.1.4 always_noconv
Remarks
Returns true if no conversion will be done.
7.4.1.8.1.5 length
Remarks
The distance between two points is returned.
7.4.1.8.1.6 max_length
Remarks
The number of elements to convert from externT to internT is returned.
Implements out.
The result is returned as a value as in Table 7-3.
Implements in.
The result is returned as a value as in Table 7-3.
Implements encoding.
Implements always_noconv.
Implements length.
Implements max_length.
Table 7-3. Convert Result Values
Value Meaning
error Encountered a from_type character it could not convert
noconv No conversion was needed
ok Completed the conversion
partial Not all source characters converted
The facet codecvt is responsible for translating internal characters ( wchar_t) to/from
external char's in a file.
There are several techniques for representing a series of wchar_t's with a series of char's.
The codecvt_byname facet can be used to select among several of the encodings. If you
construct codecvt_byname with a const char* that refers to a file, then that file is scanned by
codecvt_byname's constructor for information to customize the encoding.
If the file "en_US" exists, has codecvt data in it, and there are no syntax errors in the data,
then cvt will behave as dictated by that data. If the file exists, but does not have codecvt
data in it, then the facet will behave as if it were constructed with "C". If the file has
codecvt data in it, but there is a syntax error in the data, or if the file does not exist, then a
std::runtime_error is thrown.
For codecvt_byname<char, char, mbstate_t>, the codecvt data section begins with:
$codecvt_narrow
For codecvt_byname<wchar_t, char, mbstate_t>, the codecvt data section begins with:
$codecvt_wide
Although $codecvt_narrow is a valid data section, it really does not do anything. The
codecvt_byname<char, char, mbstate_t> facet does not add any functionality beyond
codecvt<char, char, mbstate_t>. This facet is a degenerate case of noconv (no conversion).
This can be represented in the locale data file as:
$codecvt_narrow
noconv
The facet codecvt_byname<wchar_t, char, mbstate_t> is much more interesting. After the data
section introduction ($codecvt_wide), one of these keywords can appear:
• noconv
• UCS-2
• JIS
• Shift-JIS
• EUC
• UTF-8
These keywords will be parsed as strings according to the rules for Strings and Characters
in Locale Data Files .
These Codecvt_byname keywords will be parsed as strings according to the rules for
entering strings in locale data files.
7.4.1.10.1 noconv
This conversion specifies that the base class should handle the conversion. The EWL C+
+ implementation of codecvt<wchar_t, char, mbstate_t> will I/O all bytes of the wchar_t
in native byte order.
7.4.1.10.2 UCS-2
This encoding input and outputs the two lowest order bytes of the wchar_t, high byte
first. For a big-endian, 16 bit wchar_t platform, this encoding is equivalent to noconv.
7.4.1.10.3 JIS
This is an early encoding used by the Japanese to represent a mixture of ASCII and a
subset of Kanji.
7.4.1.10.4 Shift-JIS
Another early encoding used by the Japanese to represent a mixture of ASCII and a
subset of Kanji.
7.4.1.10.5 EUC
7.4.1.10.6 UTF-8
$codecvt_wide
UTF-8
specifies that codecvt_byname<wchar_t, char, mbstate_t> will implement the UTF-8 encoding
scheme. If this data is in a file called "en_US", then the following program can be used to
output a wchar_t string in UTF-8 to a file:
Listing: Example of Writing a wchar_t String in utf-8 to a File:
#include <locale>
#include <fstream>
int main()
std::locale loc("en_US");
std::wofstream out;
out.imbue(loc);
out.open("test.dat");
54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 C3 9F
Without the UTF-8 encoding, the default encoding will take over (all wchar_t bytes in
native byte order):
#include <fstream>
int main()
{
std::wofstream out("test.dat");
out << L"This is a test \x00DF";
}
00 54 00 68 00 69 00 73 00 20 00 69 00 73 00 20
00 61 00 20 00 74 00 65 00 73 00 74 00 20 00 DF
These classes are templated simply on the internal character type (and should be
instantiated with wchar_t). The external character type is implicitly char, and the state
type is implicitly mbstate_t.
Note in An example use of __utf_8 is: that this locale (and wofstream) will have all of the
facets of the current global locale except that its codecvt<wchar_t, char, mbstate_t> will
use the UTF-8 encoding scheme. Thus the binary contents of the file is (in hex):
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 197
Standard Locale Categories
int main()
std::wofstream out;
out.imbue(loc);
out.open("test.dat");
Result
54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 C3 9F
The class num_get includes specific functions for parsing and formatting of numbers.
7.4.2.2.1 get
Remarks
returns and iterator type.
Remarks
Implements the relative versions of get.
TemplateClassNum_put
A class for formatted numeric output.
The class num_put includes specific functions for parsing and formatting of numbers.
7.4.2.3.1 put
TemplateClassNumpunct
The template class numpunct provides various functions for punctuation localizations.
7.4.2.4.1.1 decimal_point
Remarks
Returns the character used for a decimal point.
7.4.2.4.1.2 thousands_sep
Remarks
Returns the character used for the thousand separator.
7.4.2.4.1.3 grouping
Remarks
Returns a string describing the thousand separators.
7.4.2.4.1.4 truename
Remarks
Returns a string describing the localization of the word "true".
7.4.2.4.1.5 falsename
Remarks
Returns a string describing the localization of the word "false".
Implements decimal_point.
Implements thousands_sep.
Implements grouping.
Implements truename.
Implements falsename.
The facet numpunct specifies the punctuation used for parsing and formatting numeric
quantities. You can specify the decimal point character, thousands separator, the
grouping, and the spelling of true and false. If you construct numpunct_byname with a const
char* that refers to a file, then that file is scanned by numpunct_byname's constructor for
information to customize the encoding.
numpunct_byname<char> np("en_US");
If the file "en_US" exists, has numpunct data in it, and there are no syntax errors in the
data, then np will behave as dictated by that data. If the file exists, but does not have
numpunct data in it, then the facet will behave as if it were constructed with "C". If the
file has numpunct data in it, but there is a syntax error in the data, or if the file does not
exist, then a std::runtime_error is thrown.
For numpunct_byname<char>, the numpunct data section begins with:
$numeric_narrow
$numeric_wide
The syntax for both the narrow and wide data sections is the same. There are keywords
that allow you to specify the different parts of the numpunct data:
• decimal_point
• thousands_sep
• grouping
• false_name and true_name
You enter data with one of these keywords, followed by an equal sign '=', and then the
data. You can specify any or all of the keywords. Data not specified will default to that of
the "C" locale. The first two keywords (decimal_point and thousands_sep) have character
data associated with them. See the rules for Character Syntax for details. The last three
keywords have string data associated with them. See the rules for String Syntax .
Listing: Example usage of numpunct_byname
$numeric_narrow
decimal_point = ','
thousands_sep = '.'
grouping = 3|2
false_name = nope
true_name = sure
Here is an example program using the above data for narrow streams:
#include <sstream>
#include <locale>
#include <iostream>
int main()
{
std::locale loc("my_loc");
std::cout.imbue(loc);
std::istringstream in("1.23.456 nope 1.23.456,789");
in.imbue(loc);
in >> std::boolalpha;
long i;
bool b;
double d;
in >> i >> b >> d;
std::cout << i << '
<< std::boolalpha << !b << '
<< std::fixed << d;
}
1.23.456
sure
1.23.456,789000
7.4.2.4.1.7.1 decimal_point
decimal_point = '.'
7.4.2.4.1.7.2 thousands_sep
The character to be used for the thousands separator is specified with thousands_sep, as in:
thousands_sep = ','
7.4.2.4.1.7.3 grouping
The grouping string specifies the number of digits to group, going from right to left. For
example, the grouping: 321 means that the number 12345789 would be printed as in:
1,2,3,4,56,789
grouping = 321
The names of false and true can be specified with false_name and true_name. For
example:
true_name = sure
7.4.2.4.1.8 Numeric_wide
For $ numeric_wide, wide characters can be represented with the hex or universal format
(e.g. "\u64D0").
It is easy enough to derive from numpunct and override the virtual functions in a portable
manner. But numpunct also has a non-standard protected interface that you can take
advantage of if you wish.
There are five protected data members:
char_type __decimal_point_;
char_type __thousands_sep_;
string __grouping_;
A derived class could set these data members in its constructor to whatever is
appropriate, and thus not need to override the virtual methods.
Listing: Example of numpunct<char>
struct mypunct: public std::numpunct<char>
{
mypunct();
};
mypunct::mypunct()
__decimal_point_ = ',';
__thousands_sep_ = '.';
__grouping_ = "\3\2";
__falsename_ = "nope";
__truename_ = "sure";
int main()
std::cout.imbue(loc);
// ...
7.4.3.1.1 compare
Remarks
A value of 1 is returned if the first is lexicographically greater than the second. A value of
negative 1 is returned if the second is greater than the first. A value of zero is returned if
the strings are the same.
7.4.3.1.2 transform
string_type transform
(const charT* low, const charT* high) const;
Remarks
The transform member function is used for comparison of a series of strings.
Returns a string for comparison.
7.4.3.1.3 hash
Remarks
Returns the hash value of the string
int do_compare
(const charT* low1, const charT* high1,
const charT* low2, const charT* high2) const;
Implements compare.
Implements transform
Implements hash.
The facet collate is responsible for specifying the sorting rules used for sorting strings.
The base class collate does a simple lexical comparison on the binary values in the string.
collate_byname can perform much more complex comparisons that are based on the
Unicode sorting algorithm. If you construct collate_byname with a const char* that refers
to a file, then that file is scanned by collate_byname's constructor for information to
customize the collation rules.
collate_byname<char> col("en_US");
If the file "en_US" exists, has collate data in it, and there are no syntax errors in the data,
then col will behave as dictated by that data. If the file exists, but does not have collate
data in it, then the facet will behave as if it were constructed with "C". If the file has
collate data in it, but there is a syntax error in the data, or if the file does not exist, then a
std::runtime_error is thrown.
$collate_narrow
$collate_wide
The syntax for both the narrow and wide data sections is the same. The data consists of a
single string that has a syntax very similar to Java's RuleBasedCollator class. This syntax
is designed to provide a level three sorting key consistent with the sorting algorithm
specified by the Unicode collation algorithm.
The collation string rule is composed of a list of collation rules, where each rule is of
three forms:
7.4.3.2.3 Text-Argument:
7.4.3.2.4 Modifier:
There is a single modifier which is used to specify that all accents (secondary differences)
are backwards.
7.4.3.2.5 Relation:
7.4.3.2.6 Reset:
There is a single reset which is used primarily for expansions, but which can also be used
to add a modification at the end of a set of rules.
• '&': Indicates that the next rule follows the position to where the reset text-argument
would be sorted.
7.4.3.2.7 Relationals
The relationals allow you to specify the relative ordering of characters. For example, the
following string expresses that 'a' is less than 'b' which is less than 'c':
For the time being, just accept that a string should start with '<'. That rule will be both
relaxed and explained later.
Many languages (including English) consider 'a' < 'A', but only as a tertiary difference.
And such minor differences are not considered significant unless more important
differences are found to be equal. For example consider the strings:
• aa
• Aa
• ab
Since 'a' < 'A', then "aa" < "Aa". But "Aa" < "ab" because the difference between the
second characters 'a' and 'b' is more important the difference between the first
characters 'A' and 'a'. This type of relationship can be expressed in the collation rule
with:
This says that 'a' is less 'A' by a tertiary difference, and then 'b' and 'B' are greater than
'a' and 'A' by a primary difference (similarly for 'c' and 'C').
Accents are usually considered secondary differences. For example, lower case e with an
acute accent might be considered to be greater than lower case e, but only by a secondary
difference. This can be represented with a semicolon like:
Note that characters can be entered in hexadecimal or universal format. They can also be
quoted with single quotes (for example 'a'). If it is ambiguous whether a character is a
command or a text argument, adding quotes specifies that it is a text argument.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
210 Freescale Semiconductor, Inc.
Chapter 7 Localization Library
Characters not present in a rule are implicitly ordered after all characters that do appear in
a rule.
Normally primary, secondary and tertiary differences are considered left to right. But in
French, secondary differences are considered right to left. This can be specified in the
rule string by starting it with '@':
7.4.3.2.9 Contraction
Some languages sort groups of letters as a single character. Consider the two strings:
"acha" and "acia". In English they are sorted as just shown. But Spanish requires "ch" to
be considered a single character that is sorted after 'c' and before 'd'. Thus the order in
Spanish is reversed relative to English (that is "acia" < "acha"). This can be specified
like:
Taking case into account, you can expand this idea to:
7.4.3.2.10 Expansion
Some languages expand a single character into multiple characters for sorting. For
example in English the ligature 'æ' might be sorted as 'a' followed by 'e'. To represent
this in a rule, the reset character (&) is used. The idea is to reset the current sorting key to
an already entered value, and create multiple entries for the ligature. For example:
"... < a < b < c < d < e ... < z & a = æ & e = æ ..."
This rule resets the sort key to that of 'a', and then enters 'æ'. Then resets the sort key to
that of ' e' and enters 'æ' again. This rule says that 'æ' is exactly equivalent to 'a'
followed by 'e'. Alternatively ';' could have been used instead of '='. This would have
made "ae" less than "æ" but only by a secondary difference.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 211
Standard Locale Categories
Characters in the rule before the first '<' are ignorable. They are not considered during
the primary sorting. Accents and punctuation are often marked as ignorable, but given a
non-ignorable secondary or tertiary weight. For example, the default Java rule starts out
with:
"='\u200B'=\u200C=\u200D=\u200E=\u200F ...
";'\u0020';'\u00A0'..."
This completely ignores the first five characters (formatting control), and ignores except
for secondary differences the next two characters (spacing characters).
This is why all example rules up till now started with '<' (so that none of the characters
would be ignorable).
In the In the notice how the space character was entered using quotes to disambiguate it
from insignificant white space. Example of locale sorting notice how the space character
was entered using quotes to disambiguate it from insignificant white space. Example of
locale sorting
Assume the file "my_loc" has the following data in it:
$collate_narrow
The program below creates a vector of strings and sorts them both by "binary order" (just
using string's operator <), and by the custom rule above using a locale as the sorting key.
#include <locale>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::vector<std::string> v;
v.push_back("aaaaaaB");
v.push_back("aaaaaaA");
v.push_back("AaaaaaB");
v.push_back("AaaaaaA");
v.push_back("blackbird");
v.push_back("black-bird");
v.push_back("black bird");
v.push_back("blackbirds");
v.push_back("acia");
v.push_back("acha");
std::ostream_iterator<std::string> out(std::cout, "\n");
std::cout << "Binary order:\n\n";
std::sort(v.begin(), v.end());
std::copy(v.begin(), v.end(), out);
std::cout << '\n';
std::locale loc("my_loc");
std::sort(v.begin(), v.end(), loc);
std::cout << "Customized order:\n\n";
std::copy(v.begin(), v.end(), out);
std::cout << '\n';
}
Customized order:
aaaaaaA
AaaaaaA
aaaaaaB
AaaaaaB
acia
acha
blackbird
black-bird
black bird
blackbirds
__collation_rule<charT> rule_;
struct value
charT primary;
charT secondary;
charT tertiary;
public:
struct entry
: value
};
__collation_rule();
};
#include <iostream>
#include <locale>
#include <string>
struct my_collate
: public std::collate_byname<char>
my_collate();
my_collate::my_collate()
: std::collate_byname<char>("C")
int main()
std::string s1("Arnold");
std::string s2("arnold");
if (loc(s1, s2))
else
The custom facet my_collate derives from std::collate_byname<char> and sets the rule in its
constructor. That's all it has to do. For this example, a case-insensitive rule has been
constructed. The output of this program is:
Arnold == arnold
Alternatively, you could use my_collate directly (this is exactly what EWL C++'s locale
does):
Listing: Example of custom facet my_collate:
int main()
{
my_collate col;
std::string s1("Arnold");
std::string s2("arnold");
s2.data(), s2.data()+s2.size())
case -1:
break;
case 0:
break;
case 1:
break;
Arnold == arnold
• date_order
• get_time
• get_date
• get_weekday
• get_monthname
• get_year
iter_type get_time
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
iter_type get_date
(iter_type s, iter_type end,ios_base& str,
ios_base::iostate& err, tm* t) const;
iter_type get_weekday
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
iter_type get_monthname
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
• do_date_order
• do_get_time
• do_get_date
• do_get_weekday
• do_get_monthname
• do_get_year
dateorder
do_date_order() const;
The method do_date_order returns no_order. This result can be changed via derivation.
"%H:%M:%S"
iter_type do_get_date
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
"%A %B %d %T %Y"
This format string can be changed via the named locale facility, or by derivation.
iter_type do_get_weekday
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
"%A"
Although the format string can only be changed by derivation, the names of the weekdays
themselves can be changed via the named locale facility or by derivation.
iter_type do_get_monthname
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
"%B"
Although the format string can only be changed by derivation, the names of the months
themselves can be changed via the named locale facility or by derivation.
iter_type do_get_year
(iter_type s, iter_type end, ios_base& str,
ios_base::iostate& err, tm* t) const;
"%Y"
This method takes the parameters typical of the standard methods, but adds the pattern
parameter of type basic_string. The pattern is a general string governed by the rules
outlined in the section Format Parsing . Derived classes can make use of this method to
parse patterns not offered by time_get.
Listing: Derived classes example:
template <class charT, class InputIterator>
typename my_time_get<charT, InputIterator>::iter_type
my_time_get<charT, InputIterator>::do_get_date_time(
These commands follow largely from the C90 and C99 standards.
However a major difference here is that most of the commands have meaning for parsing
as well as formatting, whereas the C standard only uses these commands for formatting.
The pattern string consists of zero or more conversion specifiers and ordinary characters
(char or wchar_t). A conversion specifier consists of a % character, possibly followed by
an E or O modifier character (described below), followed by a character that determines
the behavior of the conversion specifier. Ordinary characters (non-conversion specifiers)
must appear in the source string during parsing in the appropriate place or failbit gets set.
On formatting, ordinary characters are sent to the output stream unmodified.
The E modifier can appear on any conversion specifier. But it is ignored for both parsing
and formatting.
The O modifier can appear on any conversion specifier. It is ignored for parsing, but
effects the following conversion specifiers on output by not inserting leading zeroes: %C,
%d, %D, %F, %g, %H, %I, %j, %m, %M, %S, %U, %V, %W, %y
class time_get_byname
public:
protected:
virtual ~time_get_byname();
};
Remarks
Formats a localized time.
Returns an iterator immediately beyond the last character.
Remarks
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
226 Freescale Semiconductor, Inc.
Chapter 7 Localization Library
namespace std {
template <class charT, class OutputIterator =
ostreambuf_iterator<charT> >
class time_put_byname
: public time_put<charT, OutputIterator>
{
public:
typedef charT char_type;
typedef OutputIterator iter_type;
explicit time_put_byname(const char* std_name, size_t refs = 0);
protected:
virtual ~time_put_byname();
};
}
locale loc("my_locale");
The narrow file "my_locale" can hold time data for both narrow and wide time facets.
Wide characters and strings can be represented in the narrow file using hexadecimal or
universal format (e.g. '\u06BD'). Narrow time data starts with the keyword:
$time_narrow
$time_wide
Otherwise, the format for the time data is identical for the narrow and wide data.
There are twelve keywords that allow you to enter the time facet data:
1. abrev_weekday
2. weekday
3. abrev_monthname
4. monthname
5. date_time
6. am_pm
7. time_12hour
8. date
9. time
10. time_zone
11. utc_offset
12. default_century
You enter data with one of these keywords, followed by an equal sign '=', and then the
data. You can specify any or all of the 12 keywords in any order. Data not specified will
default to that of the "C" locale.
NOTE
See String Syntax for syntax details.
7.4.4.10.1 abrev_weekday
This keyword allows you to enter the abbreviations for the weekday names. There must
be seven strings that follow this keyword, corresponding to Sun through Sat. The "C"
designation is:
7.4.4.10.2 weekday
This keyword allows you to enter the full weekday names. There must be seven strings
that follow this keyword, corresponding to Sunday through Saturday. The "C"
designation is:
7.4.4.10.3 abrev_monthname
This keyword allows you to enter the abbreviations for the month names. There must be
twelve strings that follow this keyword, corresponding to Jan through Dec. The "C"
designation is:
abrev_monthname = Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov
Dec
7.4.4.10.4 monthname
This keyword allows you to enter the full month names. There must be twelve strings that
follow this keyword, corresponding to January through December. The "C" designation
is:
monthname =
January February March April May June July
August September October November December
7.4.4.10.5 date_time
This keyword allows you to enter the parsing/formatting string to be used when %c is
encountered. The "C" locale has:
The date_time string must not contain %c, else an infinite recursion will occur.
7.4.4.10.6 am_pm
This keyword allows you to enter the two strings that designate AM and PM. The "C"
locale specifies:
am_pm = am pm
7.4.4.10.7 time_12hour
This keyword allows you to enter the parsing/formatting string to be used when %r is
encountered. The "C" locale has:
The time_12hour string must not contain %r, else an infinite recursion will occur.
7.4.4.10.8 date
This keyword allows you to enter the parsing/formatting string to be used when %x is
encountered. The "C" locale has:
The date string must not contain %x, else an infinite recursion will occur.
7.4.4.10.9 time
This keyword allows you to enter the parsing/formatting string to be used when %X is
encountered. The "C" locale has:
time = "%H:%M:%S"
The time string must not contain %X, else an infinite recursion will occur.
7.4.4.10.10 time_zone
This keyword allows you to enter two strings that designate the names of the locale's time
zones: the first being the name for the time zone when Daylight Savings Time is not in
effect, and the second name for when it is. The "C" locale has:
This means that time zone information is not available in the "C" locale.
7.4.4.10.11 utc_offset
This keyword allows you to enter two strings that designate the UTC offsets of the
locale's time zones: the first being the offset for the time zone when Daylight Savings
Time is not in effect, and the second string for when it is. The "C" locale has:
This means that UTC offset information is not available in the "C" locale.
7.4.4.10.12 default_century
This keyword allows you to enter the default century which is used to create the correct
year when parsing the %y format. This format parses a number and then computes the
year by adding it to 100*default_century. The "C" locale has:
default_century = 20
Assume a Date class. The I/O for the Date class can be written using time_get and
time_put in a portable manner. The input operator might look like:
Listing: Date Class Example Use
if (ok)
try
const std::time_get<charT>& tg =
std::use_facet<std::time_get<charT> >
(is.getloc());
std::tm t;
catch (...)
is.setstate(err);
return is;
The code extracts the time_get facet from the istream's locale and uses its get_date
method to fill a tm. If the extraction was successful, then the data is transferred from the
tm into the Date class.
Listing: The output method
bool failed;
try
const std::time_put<charT>& tp =
std::use_facet<std::time_put<charT>
>
(os.getloc());
std::tm t;
t.tm_mday = item.day();
t.tm_mon = item.month() - 1;
t.tm_wday = item.dayOfWeek();
pattern+2).failed();
catch (...)
failed = true;
if (failed)
os.setstate(std::ios_base::failbit |
std::ios_base::badbit);
return os;
After extracting the time_put facet from the ostream's locale, you transfer data from your
Date class into the tm (or the Date class could simply export a tm). Then the put method
is called with the tm and using the pattern "%x". There are several good things about the
Date's I/O methods:
• They are written in portable standard C++.
• They are culturally sensitive since they use the locale's time facets.
• They can handle narrow or wide streams.
• The streams can be in memory (e.g. stringstream) or file based streams (fstream)
• For wide file streams, routing is automatically going through a codecvt that could
(for example) be using something like UTF-8 to convert to/from the external file.
• They are relatively simple considering the tremendous flexibility involved.
With the Date's I/O done, the rest of the example is very easy. A French locale can be
created with the following data in a file named "French":
$time_narrow
date = "%A, le %d %B %Y"
weekday =
dimanche lundi mardi mercredi jeudi vendredi samedi
abrev_weekday =
dim lun mar mer jeu ven sam
monthname = j
anvier février mars avril mai juin juillet août
abrev_monthname =
jan fév mar avr mai juin juil aoû sep oct nov déc
Now a program can read and write Date's in both English and French (and the Date class
is completely ignorant of both languages).
Listing: Example of dates in English and French
#include <locale>
#include <iostream>
#include <sstream>
#include "Date.h"
int
main()
{
Date today;
in >> today;
std::cout.imbue(std::locale("French"));
std::cout << "En Paris, c'est " << today << '\n';
std::cout.imbue(std::locale("US"));
std::cout << "But in New York it is " << today << '\n';
This program reads in a Date using the "C" locale from an istringstream. Then cout is
imbued with "French" and the same Date is written out. And finally the same stream is
imbued again with a "US" locale and the same Date is written out again. The output is:
For this example the "US" locale was implemented with an empty file. This was possible
since the relevant parts of the "US" locale coincide with the "C" locale.
The behavior of the time facets can still be customized if you are on a platform that does
not support a file system, or if you do not wish to use data files for other reasons.
Naturally, you can derive from time_get and time_put and override each of the virtual
methods in a portable manner as specified by the C++ standard. Additionally you can
take advantage of the EWL C++ implementation if you wish (to make your job easier if
portability is not a concern).
The central theme of the EWL time facets design is a non-standard facet class called
std::timepunct:
Listing: Template Class Timepunct Synopsis
template <class charT>
class timepunct
: public locale::facet
public:
{return __weekday_names_[7+wday];}
{return __weekday_names_[wday];}
{return __month_names_[12+mon];}
return __month_names_[mon];}
{return __date_time_;}
{return __am_pm_[hour/12];}
{ return __12hr_time_;}
{return __date_;}
{return __time_;}
{return __time_zone_[isdst];}
{return __utc_offset_[bool(isdst)];}
{return __default_century_;}
protected:
virtual ~timepunct() {}
string_type __weekday_names_[14];
string_type __month_names_[24];
string_type __am_pm_[2];
string_type __date_time_;
string_type __date_;
string_type __time_;
string_type __12hr_time_;
string_type __time_zone_[2];
string_type __utc_offset_[2];
int __default_century_;
};
This class is analogous to numpunct and moneypunct. It holds all of the configurable
data. The facets time_get and time_put refer to timepunct for the data and then behave
accordingly. All of the data in timepunct is protected so that the constructor of a derived
facet can set this data however it sees fit. The timepunct facet will set this data according
to the "C" locale.
Both the full weekday names and the abbreviated weekday names are stored in
__weekday_names_. The full names occupy the first seven elements of the array, and the
abbreviated names get the last seven slots. Similarly for __month_names_.
The __am_pm_ member holds the strings that represent AM and PM, in that order.
The __date_time_ member holds the formatting/parsing string for the date-and-time. This is
the member that gets queried when %c comes up. Do not put %c in this string or an infinite
recursion will occur. The default for this string is "%A %B %d %T %Y".
The __date_ member holds the formatting/parsing string for the date. This is the member
that gets queried when %x comes up. Do not put %x in this string or an infinite recursion
will occur. The default for this string is " %A %B %d %Y".
The __time_ member holds the formatting/parsing string for the time. This is the member
that gets queried when %X comes up. Do not put %X in this string or an infinite recursion
will occur. The default for this string is " %H:%M:%S".
The __12hr_time_ member holds the formatting/parsing string for the 12-hour-time. This is
the member that gets queried when %r comes up. Do not put %r in this string or an
infinite recursion will occur. The default for this string is "%I:%M:%S %p".
The __time_zone_ member contains two strings. The first is the name of the time zone
when Daylight Savings Time is not in effect. The second string is the name of the time
zone when Daylight Savings Time is in effect. These can be used to parse or format the
tm_isdst member of a tm. These strings may be empty (as they are in the "C" locale) which
means that time zone information is not available.
The __utc_offset_ member contains two strings. The first represents the UTC offset when
Daylight Savings Time is not in effect. The second string is the offset when Daylight
Savings Time is in effect. These can be used to parse or format the tm_isdst member of a
tm. These strings may be empty (as they are in the "C" locale) which means that UTC
offset information is not available.
The final member, __default_century_ is an int representing the default century to assume
when parsing a two digit year with %y. The value 19 represents the 1900's, 20 represent's
the 2000's, etc. The default is 20.
It is a simple matter to derive from timepunct and set these data members to whatever
you see fit.
7.4.4.12 Timepunct_byname
You can use timepunct_byname to get the effects of a named locale for time facets instead of
using a named locale.
The time_get_byname and time_put_byname facets do not add any functionality over time_get
and time_put.
Listing: Using Timepunct_byname
#include <locale>
#include <iostream>
#include <sstream>
#include "Date.h"
int
main()
Date today;
in >> today;
std::cout.imbue(std::locale(std::locale(),
new std::timepunct_byname<char>("French")));
std::cout << "En Paris, c'est " << today << '\n';
std::cout.imbue(std::locale(std::locale(),
new std::timepunct_byname<char>("US")));
std::cout << "But in New York it is " << today << '\n';
This has the exact same effect as the named locale example.
But the timepunct_byname example still uses the files "French" and "US". Below is an
example timepunct derived class that avoids files but still captures the functionality of the
above examples.
Listing: Example Timepunct Facet Use
// The first job is to create a facet derived from timepunct
// that stores the desired data in the timepunct:
class FrenchTimepunct
: public std::timepunct<char>
public:
FrenchTimepunct();
FrenchTimepunct::FrenchTimepunct()
__weekday_names_[0] = "dimanche";
__weekday_names_[1] = "lundi";
__weekday_names_[2] = "mardi";
__weekday_names_[3] = "mercredi";
__weekday_names_[4] = "jeudi";
__weekday_names_[5] = "vendredi";
__weekday_names_[6] = "samedi";
__weekday_names_[7] = "dim";
__weekday_names_[8] = "lun";
__weekday_names_[9] = "mar";
__weekday_names_[10] = "mer";
__weekday_names_[11] = "jeu";
__weekday_names_[12] = "ven";
__weekday_names_[13] = "sam";
__month_names_[0] = "janvier";
__month_names_[1] = "février";
__month_names_[2] = "mars";
__month_names_[3] = "avril";
__month_names_[4] = "mai";
__month_names_[5] = "juin";
__month_names_[6] = "juillet";
__month_names_[7] = "août";
__month_names_[8] = "septembre";
__month_names_[9] = "octobre";
__month_names_[10] = "novembre";
__month_names_[11] = "décembre";
__month_names_[12] = "jan";
__month_names_[13] = "fév";
__month_names_[14] = "mar";
__month_names_[15] = "avr";
__month_names_[16] = "mai";
__month_names_[18] = "juil";
__month_names_[19] = "aoû";
__month_names_[20] = "sep";
__month_names_[21] = "oct";
__month_names_[22] = "nov";
__month_names_[23] = "déc";
int main()
Date today;
in >> today;
std::cout.imbue(std::locale(std::locale(),
new FrenchTimepunct));
std::cout << "En Paris, c'est " << today << '\n';
std::cout.imbue(std::locale::classic());
std::cout << "But in New York it is " << today << '\n';
Here we have explicitly asked for the classic locale, instead of the "US" locale since the
two are the same (but executing classic() does not involve file I/O). Using the global
locale (locale()) instead of classic() would have been equally fine in this example.
• class money_base;
• template <class charT, class InputIterator = istreambuf_iterator<charT> > class
money_get;
• template <class charT, class OutputIterator = ostreambuf_iterator<charT> > class
money_put;
• template <class charT, bool International = false> class moneypunct;
• template <class charT, bool International = false> class moneypunct_byname;
The first of these (money_base) is not a facet, but the remaining four are. The
money_base class is responsible only for specifying pattern components that will be used
to specify how monetary values are parsed and formatted (currency symbol first or last,
etc.).
The facets money_get and money_put are responsible for parsing and formatting
respectively. Though their behavior is made up of virtual methods, and thus can be
overridden via derivation, it will be exceedingly rare for you to feel the need to do so.
Like the numeric facets, the real customization capability comes with the "punct" classes:
moneypunct and moneypunct_byname.
A user-defined Money class (there will be an example later on) can use money_get and
money_put in defining its I/O, and remain completely ignorant of whether it is dealing
with francs or pounds. Instead clients of Money will imbue a stream with a locale that
specifies this information. On I/O the facets money_get and money_put query
moneypunct (or moneypunct_byname) for the appropriate locale-specific data. The
Money class can remain blissfully ignorant of cultural specifics, and at the same time,
serve all cultures!
The very reason that we can design a Money class before we know the details of
moneypunct customization is because the Money class can remain completely ignorant of
this customization.
This Money class is meant only to demonstrate I/O. Therefore it is as simple as possible.
We begin with a simple struct:
Listing: A example demonstration of input and output
struct Money
{
};
// The I/O methods for this class follow a fairly standard formula,
std::basic_istream<charT,traits>&
if (ok)
try
const std::money_get<charT>& mg =
catch (...)
is.setstate(err);
return is;
std::basic_ostream<charT, traits>&
if (ok)
bool failed;
try
const std::money_put<charT>& mp =
std::use_facet<std::money_put<charT> >(os.getloc());
item.amount_).failed();
catch (...)
failed = true;
if (failed)
os.setstate(std::ios_base::failbit |
std::ios_base::badbit);
return os;
The extraction operator ( >>) obtains a reference to money_get from the stream's locale, and
then simply uses its get method to parse directly into Money's amount_. The insertion
operator ( <<) does the same thing with money_put and its put method. These methods are
extremely flexible, as all of the formatting details (save one) are saved in the stream's
locale. That one detail is whether we are dealing a local currency format, or an
international currency format. The above methods hard wire this decision to "local" by
specifying false in the get and put calls. The moneypunct facet can store data for both of
these formats. An example difference between an international format and a local format
is the currency symbol. The US local currency symbol is "$", but the international US
currency symbol is "USD ".
For completeness, we extend this example to allow client code to choose between local
and international formats via a stream manipulator. See Matt Austern's excellent C/C++
Users Journal article: The Standard Librarian: User-Defined Format Flags for a complete
discussion of the technique used here.
To support the manipulators, our simplistic Money struct is expanded in the following
code example.
Listing: Example of manipulator support.
struct Money
{
{flag(s) = f;}
{return static_cast<format>(flag(s));}
};
An enum has been added to specify local or international format. But this enum is only
defined within the Money class. There is no format data member within Money. That
information will be stored in a stream by clients of Money. To aid in this effort, three static
methods have been added: set_format, get_format and flag. The first two methods simply
call flag which has the job of reading and writing the format information to the stream.
Although flag is where the real work is going on, its definition is surprisingly simple.
Listing: Money class flag
long&
Money::flag(std::ios_base& s)
return s.iword(n);
As described in Austern's C/C++ User Journal article, flag uses the stream's xalloc facility
to reserve an area of storage which will be the same location in all streams. And then it
uses iword to obtain a reference to that storage for a particular stream. Now it is easier to
see how set_format and get_format are simply writing and reading a long associated with
the stream s.
To round out this manipulator facility we need the manipulators themselves to allow
client code to write statements like:
{
Money::set_format(s, Money::local);
return s;
}
{
Money::set_format(s, Money::international);
return s;
}
And finally, we need to modify the Money inserter and extractor methods to read this
information out of the stream, instead of just blindly specifying false (local) in the get
and put methods.
Listing: Money class inserters and extractors
{
typename std::basic_istream<charT,traits>::sentry ok(is);
if (ok)
{
std::ios_base::iostate err = std::ios_base::goodbit;
try
{
const std::money_get<charT>& mg =
mg.get(is, 0, Money::get_format(is) ==
{
err |= std::ios_base::badbit |
std::ios_base::failbit;
}
is.setstate(err);
}
return is;
}
template<class charT, class traits>
std::basic_ostream<charT, traits>&
{
std::basic_ostream<charT, traits>::sentry ok(os);
if (ok)
{
bool failed;
try
{
const std::money_put<charT>& mp =
std::use_facet<std::money_put<charT> >(os.getloc());
item.amount_).failed();
}
catch (...)
if (failed)
os.setstate(std::ios_base::failbit |
std::ios_base::badbit);
}
return os;
}
Because we gave the enum Money::local the value 0, this has the effect of making local the
default format for a stream.
We now have a simple Money class that is capable of culturally sensitive input and
output, complete with local and international manipulators! To motivate the following
sections on how to customize moneypunct data. Below is sample code that uses our
Money class, along with the named locale facility:
Listing: Example of using a money class
int main()
{
std::istringstream in("USD (1,234,567.89)");
Money money;
std::cout.imbue(std::locale("Norwegian"));
$-1,234,567.89
USD (1,234,567.89)
-1 234 567,89 kr
NOK (1 234 567,89)
The template class money_get is used for locale monetary input routines.
public:
protected:
~money_get(); //virtual
};
7.4.5.2.1.1 get
Remarks
Returns an iterator immediately beyond the last character recognized as a valid monetary
quantity.
Remarks
Implements a localized monetary get function.
The template class money_put is used for locale monetary output routines.
public:
protected:
~money_put(); //virtual
virtual iter_type
virtual iter_type
};
7.4.5.3.1.1 put
Remarks
Returns an iterator immediately beyond the last character recognized as a valid monetary
quantity.
Remarks
Implements a localized put function.
public:
};
public:
protected:
};
7.4.5.4.1.1 decimal_point
Remarks
Returns a char to be used as a decimal point.
7.4.5.4.1.2 thousands_sep
Remarks
The character to be used for the thousands separator is specified with thousands_sep.
Returns the character to use for a thousandths separator.
7.4.5.4.1.3 grouping
Remarks
The grouping string specifies the number of digits to group, going from right to left.
Returns the string that determines the grouping of thousands.
7.4.5.4.1.4 curr_symbol
Remarks
Returns the string of the localized currency symbol.
7.4.5.4.1.5 positive_sign
Remarks
Returns the string of the localized positive sign.
7.4.5.4.1.6 negative_sign
Remarks
7.4.5.4.1.7 frac_digits
Remarks
Returns the string of the localized fractional digits.
7.4.5.4.1.8 pos_format
Remarks
These keywords allow you to enter the format for both positive and negative values.
There are 5 keywords to specify a format:
none
space
symbol
sign
value
A monetary format is a sequence of four of these keywords. Each value : symbol, sign,
value, and either space or none appears exactly once. The value none, if present, is not first;
the value space, if present, is neither first nor last. The behavior of breaking any of these
rules is undefined. The default pattern for positive values, and for local and international
formats is:
pos_format = symbol sign none value
7.4.5.4.1.9 neg_format
Remarks
These keywords allow you to enter the format for both positive and negative values.
There are 5 keywords to specify a format:
none
space
symbol
sign
value
A monetary format is a sequence of four of these keywords. Each value : symbol, sign,
value, and either space or none appears exactly once. The value none, if present, is not first;
the value space, if present, is neither first nor last. The behavior of breaking any of these
rules is undefined. The default pattern for negative values, and for local and international
formats is:
neg_format = symbol sign none value
Implements decimal_point.
Implements thousands_sep.
Implements grouping.
Implements cur_symbol.
Implements positive_sign.
Implements frac_digits.
Implements pos_format.
Implements neg_format.
It is easy enough to derive from moneypunct and override the virtual functions in a
portable manner.
But moneypunct also has a non-standard protected interface that you can take advantage
of if you wish. There are nine protected data members:
charT __decimal_point_;
charT __thousands_sep_;
string __grouping_;
string_type __cur_symbol_;
string_type __positive_sign_;
string_type __negative_sign_;
int __frac_digits_;
pattern __pos_format_;
pattern __neg_format_;
A derived class could set these data members in its constructor to whatever is
appropriate, and thus not need to override the virtual methods.
Listing: Extending Moneypunct by derivation
struct mypunct
: public std::moneypunct<char, false>
{
mypunct();
};
mypunct::mypunct()
__decimal_point_ = ',';
__cur_symbol_ = "kr";
int
main()
{
std::locale loc(std::locale(), new mypunct);
std::cout.imbue(loc);
// ...
}
Indeed, this is just what moneypunct_byname does after reading the appropriate data from a
locale data file.
public:
protected:
~moneypunct_byname(); // virtual
};
std::locale my_loc("MyLocale");
• $money_local_narrow
• $money_international_narrow
• $money_local_wide
• $money_international_wide
These data sections can appear in any order in the locale data file. And they are all
optional. Any data not specified defaults to that of the "C" locale. Wide characters and
strings can be represented in the narrow locale data file using hexadecimal or universal
format (for example, '\u06BD'). See the rules for Strings and Characters in Locale Data
Files for more syntax details.
The syntax for entering moneypunct data is the same under all four keywords.
There are 9 keywords that can be used within a $money_XXX data section to specify
moneypunct data. The keywords can appear in any order and they are all optional.
• decimal_point
• thousands_sep
• grouping
• curr_symbol
• positive_sign
• negative_sign
• frac_digits
• pos_format
• neg_format
Each of these keywords is followed by an equal sign (=) and then the appropriate data
(described below).
7.4.5.7.1 decimal_point
decimal_point = '.'
Remarks
The default decimal point is '.'
7.4.5.7.2 thousands_sep
The character to be used for the thousands separator is specified with thousands_sep, as in:
thousands_sep = ','
Remarks
The default thousands separator is ','
7.4.5.7.3 grouping
The grouping string specifies the number of digits to group, going from right to left.
Remarks
For example, the grouping: 321 means that the number 12345789 would be printed as in:
1,2,3,4,56,789
A grouping string of "0" or "" means: don't group. The default grouping string is "3".
7.4.5.7.4 curr_symbol
curr_symbol = $
It is customary for international currency symbols to be four characters long, but this is
not enforced by the locale facility. The default local currency symbols is "$". The default
international currency symbol is "USD ".
7.4.5.7.5 positive_sign
The string to be used for the positive sign is specified by positive_sign. Many locales set
this as the empty string, as in:
positive_sign = ""
Remarks
The default positive sign is the empty string.
7.4.5.7.6 negative_sign
negative_sign = ()
Remarks
The precise rules for how to treat signs that are longer than one character are laid out in
the standard. Suffice it to say that this will typically enclose a negative value in
parentheses.
The default negative sign for local formats is "-", and for international formats is "()".
7.4.5.7.7 frac_digits
The number of digits to appear after the decimal point is specified by frac_digits,as in:.
frac_digits = 2
Remarks
The default value is 2.
These keywords allow you to enter the format for both positive and negative values.
Remarks
There are 5 keywords to specify a format:
none
space
symbol
sign
value
A monetary format is a sequence of four of these keywords. Each value: symbol, sign,
value, and either space or none appears exactly once. The value none, if present, is not
first; the value space, if present, is neither first nor last. The behavior of breaking any of
these rules is undefined.
The default pattern for positive and negative values, and for local and international
formats is:
Notice that in the following listing not all of the fields have been specified because the
default values for these fields were already correct. On the other hand, it does not hurt to
specify default data to improve (human) readability in the data file.
Listing: Example Data file
To have the example code run correctly, we need a file named
"Norwegian" containing the following data:
$money_local_narrow
decimal_point = ','
curr_symbol = kr
$money_international_narrow
decimal_point = ','
public:
};
class messages
: public locale::facet,
public messages_base
public:
protected:
virtual ~messages();
};
The intent is that you can use this class to read messages from a catalog. There may be
multiple sets of messages in a catalog. And each message set can have any number of
int/string pairs. But beyond that, the standard is quiet.
Does the string fn in open refer to a file? If so, what is the format of the set/msgid/string
data to be read in from the file? There is also a messages_byname class that derives from
messages. What functionality does messages_byname add over messages?
Unfortunately the answers to all of these questions are implementation defined. This
document seeks to answer those questions. Please remember that applications depending
on these answers will probably not be portable to other implementations of the standard C
++ library.
7.4.6.1.1 open
Remarks
Returns a value that may be passed to get to retrieve a message from a message catalog.
7.4.6.1.2 get
Remarks
Returns the message in the form of a string.
7.4.6.1.3 close
Implements open.
Implements get.
Implements close.
The Embedded Warrior Library for C++ has a custom implementation of messages.
The first line simply type defines messages<char> for easier reading or typing. The second
line extracts the messages facet from the "C" locale. The third line instructs the messages
facet to look for a file named "my_messages" and read message set data out of it using the
classic ("C") locale (one could specify a locale with a specialized codecvt facet for
reading the data file). If the file is not found, the open method returns -1. The facet
messages<char> reads data from a narrow file ( ifstream). The facet messages<wchar_t> reads
data from a wide file ( wifstream).
The messages data file can contain zero or more message data sets of the format:
• $set setid
• msgid message
• msgid message
• msgid message
• ...
The keyword $set begins a message data set. The setid is the set number. It can be any int.
Set id's do not need to be contiguous. But the set id must be unique among the sets in this
catalog.
The msgid is the message id number. It can be any int. Message id's do not need to be
contiguous. But the message id must be unique among the messages in this set.
The message is an optionally quoted (") string that is the message for this setid and
msgid. If the message contains white space, it must be quoted. The message can have
characters represented escape sequences using the hexadecimal or universal format. For
example (see also String Syntax ):
"\u0048\u0069\u0020\u0054\u0068\u0065\u0072\u0065\u0021"
The message data set terminates when the data is not of the form
msgid message
Thus, there are no syntax errors in this data. Instead, a syntax error is simply interpreted
as the end of the data set. The catalog file can contain data other than message data sets.
The messages facet will scan the file until it encounters $set setid.
Listing: Example of message facet
1 "First Message"
2 "Error in foo"
3 Baboo
4 "\u0048\u0069\u0020\u0054\u0068\u0065\u0072\u0065\u0021"
$set 2
1 Ok
2 Cancel
A program that uses messages to read and output this file follows:
#include <locale>
#include <iostream>
int main()
{
typedef std::messages<char> Msg;
const Msg& ct = std::use_facet<Msg>(std::locale::classic());
Msg::catalog cat = ct.open("my_messages",
std::locale::classic());
if (cat < 0)
{
std::cout << "Can't open message file\n";
return 1;
}
std::string eof("no more messages");
for (int set = 1; set <= 2; ++set)
{
std::cout << "set " << set << "\n\n";
for (int msgid = 1; msgid < 10; ++msgid)
{
std::string msg = ct.get(cat, set, msgid, eof);
if (msg == eof)
1 First Message
2 Error in foo
3 Baboo
4 Hi There!
set 2
1 Ok
2 Cancel
public:
protected:
~messages_byname(); // virtual
};
You can use this to place the quadruple ( c, set, msgid, string) into messages' database.
The constructor of the derived facet can fill the database using multiple calls to __set.
Below is an example of such a class. This example also overrides do_open to double check
that the catalog name is a valid name, and then return the proper catalog number. And
do_close is also overridden to do nothing. The messages destructor will reclaim all of the
memory used by its database:
The main program (client code) in the Example of extending message by derivation is
nearly identical to the previous example. Here we simply create and use the customized
messages facet. Alternatively we could have created a locale and installed this facet into
it. And then extracted the facet back out of the locale using use_facet as in the first
example.
Listing: Example of extending message by derivation
#include <locale>
#include <iostream>
#include <string>
#include <map>
class MyMessages
: public std::messages<char>
public:
MyMessages();
private:
};
MyMessages::MyMessages()
catalogs_["my_messages"] = 1;
MyMessages::catalog
std::map<std::string, catalog>::const_iterator i =
catalogs_.find(fn);
if (i == catalogs_.end())
return -1;
return i->second;
int main()
Msg ct;
std::locale::classic());
if (cat < 0)
if (msg == eof)
break;
ct.close(cat);
set 2
The C++ header <clocale> are the same as the C header locale but in standard
namespace.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Container Requirements
• Sequences
• Associative Containers
• Template Class Bitset
The member function get_allocator() returns a copy of the Allocator object used in
construction of the container.
If an iterator type of the container is bi-directional or a random access iterator the
container is reversible.
A sequence is a kind of container that organizes a finite set of objects, all of the same
type, into a strictly linear arrangement.
The Library includes three kinds of sequence containers vector, lists, deque and adaptors
classes.
X(static_cast<typename X::size_type>(f),
static_cast<typename X::value_type>(l),a)
8.2 Sequences
8.2.1.1 Constructors
8.2.1.2 assign
DequeCapacity
The class deque has one member function to resize the deque.
8.2.1.3 resize
DequeModifiers
The deque class has member functions to modify the deque.
8.2.1.4 insert
8.2.1.5 erase
Remarks
An iterator to the position erased.
DequeSpecializedAlgorithms
Deque has one specialize swap function.
8.2.1.6 swap
A list is a sequence that supports bidirectional iterators and allows insert and erase
operations anywhere within the sequence.
8.2.2.1 Constructors
The overloaded list constructors create objects of type list.
8.2.2.2 assign
The overloaded assign function allows values to be assigned to a list after construction.
ListCapacity
The list class provides for one member function to resize the list.
8.2.2.3 resize
ListModifiers
The list class has several overloaded functions to allow modification of the list object.
8.2.2.4 insert
8.2.2.5 push_front
The push_front member function pushes a value at the front of the list.
8.2.2.6 push_back
The push_back member function pushes a value onto the end of the list.
8.2.2.7 erase
Remarks
Returns an iterator to the last position.
8.2.2.8 pop_front
The pop_front member function removes a value from the top of the list.
void pop_front();
8.2.2.9 pop_back
The pop_back member function removes a value from the end of the list.
void pop_back();
8.2.2.10 clear
void clear();
ListOperations
The list class provides for operations to manipulate the list.
8.2.2.11 splice
void splice
(iterator position, list<T,Allocator>& x);
void splice
(iterator position, list<T,Allocator>& x,iterator i);
void splice
(iterator position, list<T,Allocator>& x,
iterator first, iterator last);
8.2.2.12 remove
8.2.2.13 remove_if
8.2.2.14 unique
void unique();
template <class BinaryPredicate>
void unique(BinaryPredicate binary_pred);
8.2.2.15 merge
8.2.2.16 reverse
void reverse();
8.2.2.17 sort
Sorts a list according to the Compare function or by less than value for the parameterless
version.
void sort();
template <class Compare> void sort(Compare comp);
ListSpecializedAlgorithms
The list class provides a swapping function.
8.2.2.18 swap
Changes the position of the first argument with the second argument.
Container adaptors take a Container template parameter so that the container is copied
into the Container member of each adaptor.
8.2.4.1 operator ==
A user supplied operator for the queue class that compares the queue's data member.
bool operator ==
Remarks
Returns true if the data members are equal.
A user supplied operator for the queue class that compares the queue's data member.
Remarks
Returns true if the data member is less than the compared queue.
You can instantiate any priority_queue with any sequence that has random access iterator
and supporting operations front(), push_back() and pop_back().
8.2.5.1 Constructors
priority_queuemembers
The class priority_queue provides public member functions for manipulation the
priority_queue.
8.2.5.2 push
8.2.5.3 pop
void pop();
8.2.6.1.1 Constructors
Creates an object of type stack with a container object.
8.2.6.1.2 empty
Remarks
Returns true if there are no elements in the stack.
8.2.6.1.3 size
Remarks
Returns the number of elements in a stack.
8.2.6.1.4 top
Remarks
Returns the value at the top of the stack.
8.2.6.1.5 push
8.2.6.1.6 pop
void pop();
8.2.7.1 Constructors
The vector class provides overloaded constructors for creation of a vector object.
8.2.7.2 assign
The member function assign allows you to assign values to an already created object.
8.2.7.3 capacity
Remarks
Returns the maximum number of elements the vector can hold.
8.2.7.4 resize
Resizes a vector if a second argument is give the elements are filled with that value.
VectorModifiers
The vector class provides various member functions for vector data manipulation.
8.2.7.5 insert
The member function insert inserts a value or a range of values at a set position.
8.2.7.6 erase
VectorSpecializedAlgorithms
The vector class provides for a specialized swap function.
8.2.7.7 swap
Swaps the data of one argument with the other argument.
A EWL bitvector class is available for efficient bool vector manipulations. Refer to
Bitvector Class Library for more information.
The map class is an associative container that supports unique keys and provides for
retrieval of values of another type T based on the keys.
The map template class supports bidirectional iterators.
The template class map satisfies all of the requirements of a normal container and those
of a reversible container, as well as an associative container.
A map also provides operations for unique keys.
8.3.1.1 Constructors
The map class provides an overloaded constructor for creating an object of type map.
8.3.1.2.1 operator []
Remarks
Returns the value at the position indicated.
8.3.1.3.1 find
Remarks
Returns the position where the element is found.
8.3.1.3.2 lower_bound
Finds the first position where an element based upon a key would be inserted.
Remarks
Returns the first position where an element would be inserted.
8.3.1.3.3 upper_bound
Finds the last position where an element based upon a key would be inserted.
Remarks
Returns the last position where an element would be inserted.
8.3.1.3.4 equal_range
Finds both the first and last position in a range where an element based upon a key would
be inserted.
Remarks
Returns a pair of elements representing a range for insertion.
8.3.1.4.1 swap
Swaps the first argument with the second argument.
A multimap container supports equivalent keys that may contain multiple copies of the
same key value. Multimap provides for fast retrieval of values of another type based on
the keys.
8.3.2.1 Constructors
explicit multimap
(const Compare& comp = Compare(),
const Allocator& = Allocator());
template <class InputIterator> multimap
(InputIterator first, InputIterator last,
const Compare& comp = Compare(),
const Allocator& = Allocator()0;
8.3.2.2.1 find
Remarks
Returns the position where the element is at.
8.3.2.2.2 lower_bound
Finds the first position where an element based upon a key would be inserted.
Remarks
Returns the position where an element was found.
8.3.2.2.3 equal_range
Finds the first and last positions where a range of elements based upon a key would be
inserted.
Remarks
Returns a pair object that represents the first and last position where a range is found.
8.3.2.3.1 swap
The template class set is a container that supports unique keys and provides for fast
retrieval of the keys themselves.
8.3.3.1 Constructors
The set class includes overloaded constructors for creation of a set object.
explicit set
(const Compare& comp = Compare(),
const Allocator& = Allocator());
template <class InputIterator> set
(InputIterator first, last,
const Compare& comp = Compare(),
const Allocator& = Allocator());
8.3.3.2.1 swap
The template class multiset is an associative container that supports equivalent keys and
retrieval of the keys themselves.
8.3.4.1 Constructors
The multiset class includes overloaded constructors for creation of a multiset object.
explicit multiset
(const Compare& comp = Compare(),
const Allocator& = Allocator());
template <class InputIterator> multiset
(InputIterator first, last, const Compare& comp = Compare(),
const Allocator& = Allocator());
8.3.4.2.1 swap
The template class bitset can store a sequence consisting of a fixed number of bits.
In the bitset class each bit represents either the value zero (reset) or one (set), there is no
negative position.You can toggle a bit to change the value.
When converting between an object of class bitset and an integral value, the integral
value corresponding to two or more bits is the sum of their bit values.
The bitset functions can report three kinds of errors as exceptions.
• An invalid_argument exception
• An out_of_range error exception
• An overflow_error exceptions
See Exception Classes, for more information on exception classes.
8.3.5.1 Constructors
The bitset class includes overloaded constructors for creation of a bitset object.
bitset();
bitset(unsigned long val);
template <class charT, class traits, class Allocator>
explicit bitset
(const basic_string<charT, traits, Allocator>& str,
typename basic_string
<charT, traits, Allocator>::size_type pos = 0,
typename basic_string<charT, traits,
Allocator>::size_type n = basic_string
<charT, traits, Allocator>::npos);
Remarks
Returns the result of the "and equals" operation.
8.3.5.2.2 operator |=
Remarks
Assigns the result of the "bitwise OR" of the left and right operands to the left operand.
8.3.5.2.3 operator ^=
Remarks
Returns the result of the "exclusive or equals" operation.
Remarks
Returns the result of the "left shift equals" operation.
Remarks
Returns the result of the "right shifts equals" operation.
8.3.5.2.6 Set
bitset<N>& set();
bitset<N>& set(size_t pos, int val = 1);
Remarks
For the function with no parameters sets all the bits to true. For the overloaded function
with just a position argument sets that bit to true. For the function with both a position
and a value sets the bit at that position to the value.
Returns the altered bitset.
8.3.5.2.7 reset
bitset<N>& reset();
bitset<N>& reset(size_t pos);
Remarks
The reset function without any arguments sets all the bits to false. The reset function with
an argument sets the bit at that position to false.
Returns the modified bitset.
8.3.5.2.8 operator ~
Remarks
Returns the modified bitset.
8.3.5.2.9 flip
bitset<N>& flip();
bitset<N>& flip(size_t pos);
Remarks
Returns the modified bitset.
8.3.5.2.10 to_ulong
Remarks
Returns the unsigned long value that the bitset represents.
8.3.5.2.11 to_string
Gives the string as zero and ones that the bitset represents.
Remarks
Returns a string that the bitset represents.
8.3.5.2.12 count
Remarks
Returns the number of set bits.
8.3.5.2.13 size
Remarks
Returns the size of the bitset.
8.3.5.2.14 operator ==
Remarks
Returns true if the argument is equal to the right side bitset.
8.3.5.2.15 operator !=
Remarks
Returns true if the argument is not equal to the right side bitset.
8.3.5.2.16 test
Remarks
Returns true if the bit at the position is true.
8.3.5.2.17 any
Remarks
Returns true if any bits in the bitset are true.
8.3.5.2.18 none
Remarks
Returns true if all bits are false.
Remarks
Returns the modified bitset.
Remarks
Returns the modified bitset.
Remarks
Returns the modified bitset.
8.3.5.3.2 operator |
A bitwise or operator.
Remarks
Returns the modified bitset.
8.3.5.3.3 operator ^
Remarks
Returns the modified bitset.
Remarks
Returns the bitset.
Remarks
Returns the bitset.
This chapter presents the concept of iterators in detail, defining and illustrating the five
iterator categories of input iterators, output iterators, forward iterators, bidirectional
iterators and random access iterators.
This chapter describes the components used in C++ programs to perform iterations for
container classes, streams and stream buffers.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Requirements
• Header iterator
• Iterator Primitives
• Predefined Iterators
• Stream Iterators
• _EWL_RAW_ITERATORS
9.1 Requirements
Iterators are a generalized pointer that allow the C++ program to work with various
containers in a unified manner.
All iterators allow the dereference into a value type.
Since iterators are an abstraction of a pointer all functions that work with regular pointers
work equally with regular pointers.
There are requirements for input iterators, this manual, does not attempt to list them all.
Algorithms on input iterators should never attempt to pass through the same iterator more
than once.
There are requirements for output iterators, this manual, does not attempt to list them all.
An output iterator is assignable.
Forward iterators meet all the requirements of input and output iterators.
There are requirements for forward iterators, this manual, does not attempt to list them
all.
The header iterator includes classes, types and functions used to allow the C++ program
to work with various containers in a unified manner.
iterator_traits<Iterator>::difference_type
iterator_traits<Iterator>::value_type
iterator_traits<Iterator>::iterator_category
are defined as the iterator's difference type, value type and iterator category, respectively.
In the case of an output iterator, the types
iterator_traits<Iterator>::difference_type
iterator_traits<Iterator>::value_type
defined as void.
The template iterator_traits<Iterator> is specialized for pointers and for pointers to const
The iterator template may be used as a base class for new iterators.
9.3.4.1 advance
9.3.4.2 distance
Remarks
The distance from last must be reachable from first.
The number of increments from first to last.
• Reverse iterators
• Insert Iterators
Both bidirectional and random access iterators have corresponding reverse iterator
adaptors that they iterate through.
9.4.1.3 Constructors
9.4.1.4 base
Remarks
The current iterator is returned.
Operator++
reverse_iterator& operator++();
reverse_iterator operator++(int);
reverse_iterator& operator--();
reverse_iterator operator--(int);
reverse_iterator operator+
(typename reverse_iterator<Iterator>::difference_type n)
const;
Operator+=
reverse_iterator& operator+=
(typename reverse_iterator<Iterator>::difference_type n);
iterator operator-
(typename reverse_iterator<Iterator>::difference_type n)
const;
reverse_iterator& operator-=
(typename reverse_iterator<Iterator>
::difference_type n);
reference operator[]
(typename reverse_iterator<Iterator>::difference_type n)
const;
A bool true value is returned if the first iterator is less than the second.
Operator!=
A bool true value is returned if the first iterator is not equal to the second.
Operator>
A bool true value is returned if the first iterator is greater than the second.
Operator>=
Insert iterators, are provided to make it possible to deal with insertion in the same way as
writing into an array.
9.4.2.2 Constructors
9.4.2.2.1 operator =
back_insert_iterator<Container>& operator=
(typename Container::const_reference value);
Remarks
A reference to the copied back_insert_iterator is returned.
9.4.2.3.1 Operator *
back_insert_iterator<Container>& operator*();
9.4.2.3.2 Operator ++
back_insert_iterator<Container>& operator++();
back_insert_iterator<Container> operator++(int);
9.4.2.4 back_inserter
Remarks
The back_insert_iterator is returned.
9.4.3.1 Constructors
Creates a front_insert_iteratorobject.
Operator=
Assigns a value to a front_insert_iterator object.
front_insert_iterator<Container>& operator=
Remarks
A front_insert_iterator copy of the const_reference value is returned.
front_insert_iterator<Container>& operator*();
front_insert_iterator<Container>& operator++();
front_insert_iterator<Container> operator++(int);
Remarks
A post or pre increment operator.
The this pointer is returned.
9.4.3.3 front_inserter
Remarks
The front_insert_iteraor is returned.
9.4.4.1 Constructors
insert_iterator
(Container& x, typename Container::iterator i);
operator=
An operator for assignment of a const_reference value.
insert_iterator<Container>& operator=
(typename Container::const_reference value);
Remarks
Returns a copy of the insert_iterator.
insert_iterator<Container>& operator*();
Operator++
insert_iterator<Container>& operator++();
insert_iterator<Container>& operator++(int);
9.4.4.3 inserter
Remarks
The inserter iterator is returned.
Input and output iterators are provided to make it possible for algorithmic templates to
work directly with input and output streams.
An istream_iterator reads (using operator>>) successive elements from the input stream. It
reads after it is constructed, and every time the increment operator is used.
9.5.1.1 Constructors
istream_iterator();
istream_iterator(istream_type& s);
istream_iterator
(const istream_iterator<T, charT,traits,Distance>& x);
The parameterless iterator is the only legal constructor for an end condition.
9.5.1.2 destructor
~istream_iterator();
Operator==
The ostream_iterator writes (using operator<<) successive elements onto the output stream.
9.5.2.1 Constructors
ostream_iterator(ostream_type& s);
ostream_iterator(ostream_type& s, const charT* delimiter);
ostream_iterator(const ostream_iterator& x);
Operator=
ostream_iterator& operator=(const T& value);
9.5.2.2 destructor
Removes and instance of an ostream_iterator object.
~ostream_iterator();
Operator*
ostream_iterator& operator*();
ostream_iterator& operator++();
ostream_iterator& operatot++(int);
The istreambuf_iterator reads successive characters from the istreambuf object for which it
was constructed.
9.5.3.1 Constructors
istreambuf_iterator() throw();
istreambuf_iterator(basic_istream<charT,traits>& s) throw();
istreambuf_iterator(basic_streambuf<charT,traits>* s)
throw();
istreambuf_iterator(const proxy& p) throw();
istreambuf_iterator<charT,traits>&
istreambuf_iterator<charT,traits>::operator++();
9.5.3.3 equal
An equality comparison.
Remarks
True is returned if the arguments are equal.
The ostreambuf_iterator writes successive characters to the ostreambuf object for which it
was constructed.
9.5.4.1 Constructors
ostreambuf_iterator(ostream_type& s) throw();
ostreambuf_iterator(streambuf_type* s) throw();
Operator=
Operator*
ostreambuf_iterator<charT,traits>& operator*();
ostreambuf_iterator<charT,traits>& operator++();
ostreambuf_iterator<charT,traits>& operator++(int);
9.5.4.3 failed
Remarks
The bool false value is returned if a write failure occurs.
9.6 _EWL_RAW_ITERATORS
If _EWL_RAW_ITERATORS is defined, vector and string will use pointers for their iterators,
otherwise they will use classes.
The difference can effect argument dependent (Koenig) lookup in some cases. For
example:
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v1(10), v2(10);
copy(v1.begin(), v1.end(), v2.begin());
}
This compiles if the iterators are classes ( _EWL_RAW_ITERATORS undefined). But if the
iterators are simply pointers, a compile time error results:
To fix this code so that it works with either setting, add a std qualifier to copy:
The header algorithm provides classes, types and functions for use with the standard C++
libraries.
The standard algorithms can work with program defined data structures, as long as these
data structures have iterator types satisfying the assumptions on the algorithms.
The names of the parameters used in this chapter reflect their usage.
A predicate parameter is used for a function object that returns a value testable as true.
The binary predicate parameter takes two arguments.
10.1.1.1 for_each
Remarks
The function f is returned.
10.1.1.2 find
The function find searches for the first element that contains the value passed.
Remarks
Returns the type passed.
10.1.1.3 find_if
The function find_if searches for the first element that matches the criteria passed by the
predicate.
Remarks
Returns the iterator of the matched value.
10.1.1.4 find_end
template<class ForwardIterator1,
class ForwardIterator2>
ForwardIterator1 find_end
(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
template<class ForwardIterator1,
class ForwardIterator2,class BinaryPredicate>
ForwardIterator1 find_end
Remarks
Returns the iterator to the last value or the last1 argument if none is found.
10.1.1.5 find_first_of
template<class ForwardIterator1,
class ForwardIterator2>
ForwardIterator1 find_first_of
(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
template<class ForwardIterator1,
class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 find_first_of
(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2,
ForwardIterator2 last2, BinaryPredicate pred);
Remarks
Returns the iterator to the first value or the last1 argument if none is found.
10.1.1.6 adjacent_find
The function adjacent_find is used to search for two adjacent elements that are equal or
equal according to the predicate argument.
template<class ForwardIterator>
ForwardIterator adjacent_find
(ForwardIterator first, ForwardIterator last);
template<class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find
(ForwardIterator first, ForwardIterator last,
BinaryPredicate pred);
Remarks
Returns the iterator to the first occurrence found or to last if no occurrence is found.
10.1.1.7 count
Remarks
Returns the number of elements (iterators) as an
iterator_traits<InputIterator>::difference_type
10.1.1.8 count_if
The function count_if is used to find the number of elements that match the criteria.
Remarks
Returns the number of elements (iterators) as an
iterator_traits<InputIterator>::difference_type
10.1.1.9 mismatch
The function mismatch is used to find sequences that are not the same or differ according
to the predicate criteria.
Remarks
Returns a pair<iterator> that represent the beginning element and the range. If no
mismatch is found the end and the corresponding range element is returned.
10.1.1.10 equal
Remarks
A bool true is returned if the values are equal or meet the criteria of the predicate.
10.1.1.11 search
The function search is used to search for the first occurrence of a sub-range that meets the
criteria.
Remarks
An iterator to the first occurrence is returned or last1 is returned if no criteria is met.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 327
Header algorithm
10.1.1.12 search_n
The function search_n is used to search for a number of consecutive elements with the
same properties.
Remarks
An iterator to the first occurrence is returned or last1 is returned if no criteria is met.
10.1.2.1 copy
Remarks
The position of the last copied element is returned.
10.1.2.2 copy_backward
The function copy_backwards is used to copy a range starting with the last element.
template<class BidirectionalIterator1,
class BidirectionalIterator2>
BidirectionalIterator2 copy_backward
(BidirectionalIterator1 first,BidirectionalIterator1 last,
BidirectionalIterator2 result);
Remarks
The position of the last copied element is returned.
10.1.2.3 swap
Remarks
There is no return.
10.1.2.4 swap_ranges
Remarks
The position of the last swapped element is returned.
10.1.2.5 iter_swap
Remarks
There is no return.
10.1.2.6 transform
The function transform is used to modify and copy elements of two ranges.
template<class InputIterator,
class OutputIterator, class UnaryOperation>
OutputIterator transform
(InputIterator first, InputIterator last,
OutputIterator result, UnaryOperation op);
template<class InputIterator1,
class InputIterator2, class OutputIterator,
class BinaryOperation>
OutputIterator transform
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
Remarks
The position of the last transformed element is returned.
10.1.2.7 replace
The function replace is used to replace an element with another element of different
value.
Remarks
There is no return.
10.1.2.8 replace_copy
The function replace_copy is used to replace specific elements while copying an entire
range.
Remarks
The position of the last copied element is returned.
10.1.2.9 replace_copy_if
The function replace_copy_if is used to replace specific elements that match certain
criteria while copying the entire range.
template<class Iterator,
class OutputIterator, class Predicate, class T>
OutputIterator replace_copy_if
(Iterator first, Iterator last,
OutputIterator result,Predicate pred, const T& new_value);
Remarks
The position of the last copied element is returned.
10.1.2.10 fill
Remarks
There is no return value.
10.1.2.11 fill_n
The function fill_n is used to fill a number of elements with a specified value.
template<class OutputIterator,
class Size, class T>
void fill_n
(OutputIterator first, Size n, const T& value);
Remarks
There is no return value.
10.1.2.12 generate
The function generate is used to replace elements with the result of an operation.
Remarks
There is no return value.
10.1.2.13 generate_n
The function generate_n is used to replace a number of elements with the result of an
operation.
Remarks
There is no return value.
10.1.2.14 remove
Remarks
The end of the resulting range is returned.
10.1.2.15 remove_if
Remarks
The end of the resulting range is returned.
10.1.2.16 remove_copy
The function remove_copy is used remove elements that do not match a value during a
copy.
Remarks
The end of the resulting range is returned.
10.1.2.17 remove_copy_if
The function remove_copy_if is used to remove elements that do not match a criteria while
doing a copy.
template<class InputIterator,
class OutputIterator, class Predicate>
OutputIterator remove_copy_if
(InputIterator first, InputIterator last,
OutputIterator result, Predicate pred);
Remarks
The end of the resulting range is returned.
10.1.2.18 unique
template<class ForwardIterator>
ForwardIterator unique
(ForwardIterator first, ForwardIterator last);
template<class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first,
ForwardIterator last, BinaryPredicate pred);
Remarks
The end of the resulting range is returned.
10.1.2.19 unique_copy
Remarks
The end of the resulting range is returned.
10.1.2.20 reverse
template<class BidirectionalIterator>
void reverse
(BidirectionalIterator first,BidirectionalIterator last);
Remarks
No value is returned.
10.1.2.21 reverse_copy
The function reverse_copy is used to copy the elements while reversing their order.
Remarks
The position of the last copied element is returned.
10.1.2.22 rotate
template<class ForwardIterator>
void rotate
(ForwardIterator first, ForwardIterator middle,
ForwardIterator last);
Remarks
There is no return value.
10.1.2.23 rotate_copy
Remarks
The position of the last copied element is returned.
10.1.2.24 random_shuffle
The function random_shuffle is used to exchange the order of the elements in a random
fashion.
template<class RandomAccessIterator>
void random_shuffle
(RandomAccessIterator first,RandomAccessIterator last);
template<class RandomAccessIterator,
class RandomNumberGenerator>
void random_shuffle
(RandomAccessIterator first, RandomAccessIterator last,
RandomNumberGenerator& rand);
Remarks
No value is returned.
10.1.2.25 partition
The function partition is used to change the order of the elements so that the elements
that meet the criteria are first in order.
Remarks
Returns an iterator to the first position where the predicate argument is false.
10.1.2.26 stable_partition
The function stable_partition is used to change the order of the elements so that the
elements meet the criteria are first in order. The relative original order is preserved.
Remarks
Returns an iterator to the first position where the predicate argument is false.
All of the sorting functions have two versions:, one that takes a function object for
comparison and one that uses the less than operator.
10.1.3.1 sort
The function sort is used sorts the range according to the criteria.
template<class RandomAccessIterator>
void sort
(RandomAccessIterator first,RandomAccessIterator last);
template<class RandomAccessIterator,
class Compare>
void sort(RandomAccessIterator first,
RandomAccessIterator last, Compare comp);
Remarks
There is no return value.
10.1.3.2 stable_sort
The function stable_sort is used to sort the range but preserves the original order for
equal elements.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 337
Header algorithm
template<class RandomAccessIterator>
void stable_sort
(RandomAccessIterator first, RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void stable_sort
(RandomAccessIterator first,
RandomAccessIterator last,Compare comp);
Remarks
There is no return value.
10.1.3.3 partial_sort
The function partial_sort is used to sort a sub-range leaving the rest unsorted.
template<class RandomAccessIterator>
void partial_sort
(RandomAccessIterator first,RandomAccessIterator middle,
RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void partial_sort
(RandomAccessIterator first,RandomAccessIterator middle,
RandomAccessIterator last, Compare comp);
Remarks
There is no return value.
10.1.3.4 partial_sort_copy
Remarks
The position at the end of the copied elements is returned.
10.1.3.5 nth_element
template<class RandomAccessIterator>
void nth_element
(RandomAccessIterator first RandomAccessIterator nth,
RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void nth_element
(RandomAccessIterator first,RandomAccessIterator nth,
RandomAccessIterator last, Compare comp);
Remarks
There is no value returned.
10.1.3.6 lower_bound
The function lower_bound is used to find the first position that an element may be inserted
without changing the order.
Remarks
The position where the element can be inserted is returned.
10.1.3.7 upper_bound
The function upper_bound is used to find the last position that an element may be inserted
without changing the order.
Remarks
The position where the element can be inserted is returned.
10.1.3.8 equal_range
The function equal_range is used to find the range as a pair where an element can be
inserted without altering the order.
Remarks
The range as a pair<> where the element can be inserted is returned.
10.1.3.9 binary_search
The function binary_search is used to see if a value is present in a range or that a value
meets a criteria within that range.
Remarks
The bool value true is met if any element meets the criteria.
10.1.3.10 merge
template<class InputIterator1,
class InputIterator2, class OutputIterator>
OutputIterator merge
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template<class InputIterator1, class InputIterator2,
class OutputIterator, class Compare>
OutputIterator merge
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Return
The position of the first element not overwritten is returned.
10.1.3.11 inplace_merge
The function inplace_merge is used to merge consecutive sequences to the first for a
concatenation.
template<class BidirectionalIterator>
void inplace_merge
(BidirectionalIterator first,BidirectionalIterator middle,
BidirectionalIterator last);
template<class BidirectionalIterator, class Compare>
void inplace_merge
(BidirectionalIterator first,BidirectionalIterator middle,
BidirectionalIterator last, Compare comp);
Remarks
There is no value returned.
10.1.3.12 includes
The function includes is used to determine if every element meets a specified criteria.
Remarks
The bool value true is retuned if all values match or false if one or more does not meet
the criteria.
10.1.3.13 set_union
The function set_union is used to process the sorted union of two ranges.
template<class InputIterator1,
class InputIterator2, class OutputIterator>
OutputIterator set_union
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template<class InputIterator1, class InputIterator2,
class OutputIterator, class Compare>
OutputIterator set_union
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Remarks
The end of the constructed range is returned.
10.1.3.14 set_intersection
template<class InputIterator1,
class InputIterator2, class OutputIterator>
OutputIterator set_intersection
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template<class InputIterator1,
class InputIterator2, class OutputIterator,
class Compare>
OutputIterator set_intersection
(InputIterator1 first1, InputIterator1 last1,
Remarks
The end of the constructed range is returned.
10.1.3.15 set_difference
The function set_difference is used to process all of the elements of one range that are not
part of another range.
template<class InputIterator1,
class InputIterator2, class OutputIterator>
OutputIterator set_difference
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template<class InputIterator1,
class InputIterator2,
class OutputIterator, class Compare>
OutputIterator set_difference
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Remarks
The end of the constructed range is returned.
10.1.3.16 set_symetric_difference
The function set_symetric_difference is used to process all of the elements that are in only
one of two ranges.
template<class InputIterator1,
class InputIterator2, class OutputIterator>
OutputIterator set_symmetric_difference
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template<class InputIterator1,
class InputIterator2,
class OutputIterator, class Compare>
OutputIterator set_symmetric_difference
(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Remarks
The end of the constructed range is returned.
10.1.3.17 push_heap
template<class RandomAccessIterator>
void push_heap
(RandomAccessIterator first, RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void push_heap
(RandomAccessIterator first,
RandomAccessIterator last,Compare comp);
Remarks
There is no value returned.
10.1.3.18 pop_heap
template<class RandomAccessIterator>
void pop_heap
(RandomAccessIterator first, RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void pop_heap
(RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
Remarks
There is no value returned.
10.1.3.19 make_heap
template<class RandomAccessIterator>
void make_heap
(RandomAccessIterator first, RandomAccessIterator last);
Remarks
There is no value returned.
10.1.3.20 sort_heap
template<class RandomAccessIterator>
void sort_heap
(RandomAccessIterator first,RandomAccessIterator last);
template<class RandomAccessIterator, class Compare>
void sort_heap
(RandomAccessIterator first, RandomAccessIterator last,
Compare comp);
Remarks
Note that this result is not stable
There is no value returned.
10.1.3.21 min
The function min is used to determine the lesser of two objects by value or based upon a
comparison.
template<class T>
const T& min (const T& a, const T& b);
template<class T, class Compare>
const T& min(const T& a, const T& b, Compare comp);
Remarks
The lesser of the two objects is returned.
10.1.3.22 max
The function max is used to determine the greater of two objects by value or based upon a
comparison.
template<class T>
const T& max (const T& a, const T& b);
template<class T, class Compare>
const T& max(const T& a, const T& b, Compare comp);
Remarks
The greater of the two objects is returned.
10.1.3.23 min_element
The function min_element is used to determine the lesser element within a range based
upon a value or a comparison.
template<class ForwardIterator>
ForwardIterator min_element
(ForwardIterator first, ForwardIterator last);
template<class ForwardIterator, class Compare>
ForwardIterator min_element
(ForwardIterator first, ForwardIterator last,
Compare comp);
Remarks
The position of the element is returned.
10.1.3.24 max_element
The function max_element is used to determine the greater element within a range based
upon a value or a comparison.
template<class ForwardIterator>
ForwardIterator max_element
(ForwardIterator first, ForwardIterator last);
template<class ForwardIterator, class Compare>
ForwardIterator max_element
(ForwardIterator first, ForwardIterator last,
Compare comp);
Remarks
The position of the element is returned.
10.1.3.25 lexicographical_compare
Remarks
Returns true if the first argument is less than the second and false for all other conditions.
10.1.3.26 next_permutation
template<class BidirectionalIterator>
bool next_permutation
(BidirectionalIterator first, BidirectionalIterator last);
template<class BidirectionalIterator, class Compare>
bool next_permutation
(BidirectionalIterator first,
BidirectionalIterator last, Compare comp);
Remarks
Returns true if all elements have been sorted.
10.1.3.27 prev_permutation
template<class BidirectionalIterator>
bool prev_permutation
(BidirectionalIterator first, BidirectionalIterator last);
template<class BidirectionalIterator, class Compare>
bool prev_permutation
(BidirectionalIterator first,
BidirectionalIterator last, Compare comp);
Remarks
Returns true if all elements have been sorted.
10.1.4.1 bsearch
is replaced by
and
10.1.4.2 qsort
is replaced by
and
This chapter is a reference guide to the ANSI/ISO standard Numeric classes which are
used to perform the semi-numerical operations. This chapter is constructed in the
following sub sections and uses the ISO (International Organization for Standardization)
C++ Standard as a guide.
• Numeric type requirements
• Numeric arrays
• Generalized Numeric Operations
• C Library
A C++ program shall instantiate these components only with a type TYPE that satisfies the
following requirements:
Tis not an abstract class (it has no pure virtual member functions);
• TYPE is not a reference type;
• TYPE is not cv-qualified;
• If TYPE is a class, it has a public default constructor;
• If TYPE is a class, it has a public copy constructor with the signature TYPE::TYPE(const
TYPE&)
• If TYPE is a class, it has a public destructor;
• If TYPE is a class, it has a public assignment operator whose signature is either
or
TYPE& TYPE::operator=(TYPE)
• If TYPE is a class, the assignment operator, copy and default constructors, and
destructor shall correspond to each other as far an initialization of raw storage using
the default constructor, followed by assignment, is the equivalent to initialization of
raw storage using the copy constructor.
• Destruction of an object, followed by initialization of its raw storage using the copy
constructor, is semantically equivalent to assignment to the original object.
• If TYPE is a class, it shall not overload unary operator&.
If an operation on TYPE throws an exception then the effects are undefined.
Specific classes member functions or general functions may have other restrictions.
The numeric array library consists of several classes and non member operators for the
manipulation of array objects.
The template class valarray is a single direction smart array with element indexing
beginning with the zero element.
11.2.1.1 Constructors
valarray();
explicit valarray(size_t);
valarray(const T&, size_t);
valarray(const T*, size_t);
valarray(const valarray<T>&);
valarray(const slice_array<T>&);
valarray(const gslice_array<T>&);
valarray(const mask_array<T>&);
valarray(const indirect_array<T>&);
11.2.1.2 Destructor
~valarray();
The valarray class provides for various means of assignment to an already created object.
valarray<T>& operator=(const valarray<T>&);
Remarks
A valarray object is returned.
valarray element access
An index operator is provided for single element access of valarray objects.
11.2.1.4 operator[]
This operator provides element access for read and write operations.
T operator[](size_t) const;
T& operator[](size_t);
Remarks
A value is returned.
valarray subset operations
An index operator is provided for subset array access.
11.2.1.5 operator[]
The index operator is specialized for subset access to allow both read and write
operations.
valarray<T> operator[](slice) const;
slice_array<T> operator[](slice);
Remarks
These operators return subset of the array. Const-qualified operators return the subset as a
new valarray object, and non-const operators return a class template object which has
reference semantics to the original array.
Operator+
valarray<T> operator+() const;
11.2.2.1 size
Remarks
Returns the size of the array.
11.2.2.2 sum
T sum() const;
Remarks
Returns the sum of the array elements.
11.2.2.3 min
T min() const;
Remarks
Returns the smallest element in an array.
11.2.2.4 max
T max() const;
Remarks
Returns the largest element in an array.
11.2.2.5 shift
Returns a new array where the elements have been shifted a set amount.
Remarks
Returns the modified array.
11.2.2.6 cshift
Remarks
Returns the modified array.
11.2.2.7 apply
Remarks
This function "applies" the function specified to all the elements of an array.
Return the modified array.
11.2.2.8 resize
Remarks
If no object is provided the array is initialized with the default constructor.
Remarks
Each operator returns an array whose length is equal to the lengths of the argument arrays
and initialized with the result of applying the operator.
The valarray class provides logical operators for the comparison of like arrays.
Remarks
All of the logical operators returns a bool array whose length is equal to the length of the
array arguments. The elements of the returned array are initialized with a boolean result
of the match.
Non-member logical operators are provided to allow for variations of order of the
operation.
Remarks
The result of these operations is a bool array whose length is equal to the length of the
array argument. Each element of the returned array is the result of a logical match.
Remarks
A valarray object is returned with the individual elements initialized with the result of the
corresponding operation.
A slice is a set of indices that have three properties, a starting index, the number of
elements and the distance between the elements.
11.2.5.1 Constructors
A constructor is overloaded to initialize an object with values or without values.
slice();
slice(size_t start, size_t length, size_t stride);
slice(const slice&);
11.2.5.2.1 start
Remarks
The starting position is returned.
11.2.5.2.2 size
Remarks
The size of the slice is returned by the size member function.
11.2.5.2.3 stride
Remarks
The distance between each element is returned by stride.
The slice_array class is a helper class used by the slice subscript operator.
11.2.6.1 Constructors
private:
slice_array();
slice_array(const slice_array&);
The assignment operator allows for the initialization of a slice_array after construction.
Remarks
There is no return for the compound operators.
Remarks
No value is returned.
11.2.7.1 Constructors
gslice();
gslice(size_t start, const valarray<size_t>& lengths,
const valarray<size_t>& strides);
gslice(const gslice&);
The gslice class provides for access to the start, size and stride of the slice class.
11.2.7.2.1 start
Remarks
The starting position of the gslice is returned.
11.2.7.2.2 size
Remarks
The number of elements as a valarray is returned.
11.2.7.2.3 stride
Remarks
The size of the element as a valarray is returned.
The gslice_array class is a helper class used by the gslice subscript operator.
11.2.8.1 Constructors
gslice_array();
gslice_array(const gslice_array&);
An assignment operator is provided for initializing a gslice_array after it has been created.
Remarks
A copy of the modified gslice_array is returned for the second assignment operator.
Remarks
No return is given for the compound operators.
Remarks
There is no return for the fill function.
The mask_array class is a helper class used by the mask subscript operator.
11.2.9.1 Constructors
private:
mask_array();
mask_array(const mask_array&);
Remarks
The copy assignment operator returns a mask_array reference.
Remarks
There is no return value for the compound assignment operators.
Remarks
The indirect_array class is a helper class used by the indirect subscript operator.
11.2.10.1 Constructors
indirect_array();
indirect_array(const indirect_array&);
Remarks
The copy assignment operator returns a indirect_array reference.
Remarks
There is no return value for the compound assignment operators.
Remarks
There is no return for the fill function.
11.3.1.1 accumulate
Remarks
The sum of the values in a range or the sum of the values after being processed by an
operation is returned.
11.3.1.2 inner_product
Remarks
The value of the product starting with an initial value in a range is returned. In the
function with the operation argument it is the product after the operation is performed.
11.3.1.3 partial_sum
The first computes the partial sum and sends it to the output iterator argument.
x, y, z
x, x+y, y+z.
The second form computes according to the operational argument and sends it to the
output iterator argument. For example if the operational argument was a multiplication
operation
x, y, z
x, x*y, y*z
Remarks
The range as the result plus the last minus the first.
11.3.1.4 adjacent_difference
The first computes the adjacent difference and sends it to the output iterator argument.
x, y, z
x, y-x, z-y.
The second form computes according to the operational argument and sends it to the
output iterator argument. For example if the operational argument was a division
operation
x, y, z
x, y/x, z/y
Remarks
The range as the result plus the last minus the first.
11.4 C Library
The standard provides for the math functions included in the standard C library with
some overloading for various types.
11.4.1 <cmath>
The contents of the <cmath> headers is the same as the Standard C library headers
<math.h> with the addition to the double versions of the math functions in <cmath>, C++
adds float and long double overloaded versions of some functions, with the same
semantics.
11.4.2 <cstdlib>
The contents of the <cstdlib> headers is the same as the Standard C library headers
<stdlib.h>. In addition to the int versions of certain math functions in <cstdlib>, C++
adds long overloaded versions of some functions, with the same semantics.
Listing: The Added C++ Signatures in Cstdlib and Cmath
The header <complex> defines a template class, and facilities for representing and
manipulating complex numbers.
The header <complex> defines classes, operators, and functions for representing and
manipulating complex numbers
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Header complex shows the complex header class declarations
• Complex Specializations lists the float, double and long double specializations
• Complex Template Class is a template class for complex numbers.
12.1.1 _EWL_CX_LIMITED_RANGE
If the flag is undefined (default), then more complicated algorithms (from the C standard)
are used which have better overflow and underflow characteristics and properly
propagate infinity. Flipping this switch requires recompilation of the C++ library.
NOTE
It is recommended that ansi_prefix.xxx.h is the place to define
this flag if you want the simpler and faster multiplication and
division algorithms.
The template class complex contains Cartesian components real and imag for a complex
number.
Remarks
The effect of instantiating the template complex for any type other than float, double or
long double is unspecified. If the result of a function is not mathematically defined or not
in the range of representable values for its type, the behavior is undefined.
The complex class consists of:
• Constructors and Assignments
• Complex Member Functions
12.3.1.1 Constructors
Construct an object of a complex class.
Remarks
After construction real equal re and imag equals im.
AssignmentOperator
An assignment operator for complex classes.
Remarks
Assigns a floating point type to the Cartesian complex class.
• real
• imag
12.3.2.1 real
T real() const;
12.3.2.2 imag
T imag() const;
Several assignment operators are overloaded for the complex class manipulations.
operator+=
Adds and assigns to a complex class.
Remarks
The first operator with a scalar argument adds the scalar value of the right hand side to
the real component and stores the result in the object. The imaginary component is left
alone.
The second operator with a complex type, adds the complex value of the right hand side
to the object and stores the result in the object.
The this pointer is returned.
operator-=
Subtracts and assigns from a complex class.
Remarks
The first operator with a scalar argument subtracts the scalar value of the right hand side
from the real component and stores the result in the object. The imaginary component is
left alone.
The second operator with a complex type, subtracts the complex value of the right hand
side from the object and stores the result in the object.
The this pointer is returned.
operator*=
Multiplies by and assigns to a complex class.
Remarks
The first operator with a scalar argument multiplies the scalar value of the right hand side
to class object and stores result in the object.
The second operator with a complex type, multiplies the complex value of the right hand
side to the object and stores the result in the object.
The this pointer is returned.
operator/=
Divides by and assigns to a complex class.
Remarks
The first operator with a scalar argument divides the scalar value of the right hand side to
class object and stores result in the object.
The second operator with a complex type, divides the complex value of the right hand
side into the object and stores the result in the object.
The this pointer is returned.
Remarks
The addition performs a += operation.
Returns the complex class after the addition.
operator-
Subtracts from the complex class.
Remarks
The subtraction performs a -= operation.
Returns the complex class after the Subtraction.
operator*
Multiplies the complex class.
Remarks
The multiplication performs a *= operation.
Returns the complex class after the multiplication.
operator/
Divides from the complex class.
Remarks
The division performs a /= operation.
Returns the complex class after the division.
operator==
A boolean equality comparison.
Remarks
Returns true if the real and imaginary components are equal.
operator!=
A boolean non equality comparison.
Remarks
Returns true if the real or the imaginary components are not equal.
operator>>
Extracts a complex type from a stream.
Remarks
Extracts in the form of u, (u), or (u,v) where u is the real part and v is the imaginary part.
Any failure in extraction will set the failbit and result in undefined behavior.
operator<<
Inserts a complex number into a stream.
• real
• imag
• abs
• arg
• norm
• conj
• polar
12.3.5.1 real
Remarks
Returns the real component of the argument.
12.3.5.2 imag
Remarks
Returns the imaginary component of the argument.
12.3.5.3 abs
Remarks
Returns the absolute value of the complex class argument.
12.3.5.4 arg
Remarks
Returns the phase angle of the complex class argument or atan2(imag(x), real(x)).
12.3.5.5 norm
Remarks
The squared magnitude of the complex class.
12.3.5.6 conj
Remarks
Returns the complex conjugate of the complex class argument.
12.3.5.7 polar
template<class T>
complex<T> polar(const T&, const T&);
Remarks
Returns the complex value corresponding to a complex number whose magnitude is the
first argument and whose phase angle is the second argument.
• cos
• cosh
• exp
• log
• log10
• pow
• sin
• sinh
• sqrt
• tan
• tanh
12.3.6.1 cos
Remarks
Returns the cosine of the complex class argument.
12.3.6.2 cosh
Remarks
Returns the hyperbolic cosine of the complex class argument.
12.3.6.3 exp
Remarks
Returns the base exponential of the complex class argument.
12.3.6.4 log
template<class T>
complex<T> log (const complex<T>&);
Remarks
Returns the natural base logarithm of the complex class argument, in the range of a strip
mathematically unbounded along the real axis and in the interval of [i*pi, i*pi] along the
imaginary axis. The argument is a negative real number, imag(log(cpx)), is pi.
12.3.6.5 log10
template<class T>
complex<T> log10(const complex<T>&);
Remarks
Returns the logarithm base(10) of the argument cpx defined as log(cpx)/log(10).
12.3.6.6 pow
Remarks
Returns the complex class raised to the power of second argument defined as the
exponent of the second argument times the log of the first argument.
The value for pow(0,0)will return (nan, nan).
12.3.6.7 sin
template<class T>
complex<T> sin (const complex<T>&);
Remarks
Returns the sine of the complex class argument.
12.3.6.8 sinh
template<class T>
complex<T> sinh (const complex<T>&);
Remarks
Returns the hyperbolic sine of the complex class argument.
12.3.6.9 sqrt
template<class T>
complex<T> sqrt (const complex<T>&);
Remarks
Returns the square root of the complex class argument in the range of right half plane. If
the argument is a negative real number, the value returned lies on the positive imaginary
axis.
12.3.6.10 tan
template<class T>
complex<T> tan (const complex<T>&);
Remarks
Returns the tangent of the complex class argument.
12.3.6.11 tanh
template<class T>
complex<T> tanh (const complex<T>&);
Remarks
Returns the hyperbolic tangent of the complex class argument.
This chapter is constructed in the following subsections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Input and Output Library Summary
• Iostreams requirements
13.2.1 Definitions
Additional definitions are:
• - A unit that can represent text
character
• character container type - A class or type used to represent a character.
• iostream class templates - Templates that take two arguments: charT and traits. The
argument charT is a character container type. The argument traits is a structure which
defines characteristics and functions of the charT type.
• narrow-oriented iostream classes - These classes are template instantiation classes. The
traditional iostream classes are narrow-oriented iostream classes.
• wide-oriented iostream classes - These classes are template instantiation classes. They
are used for the character container class wchar_t.
• repositional streams and arbitrary-positional streams - A repositional stream can seek to
only a previously encountered position. An arbitrary-positional stream can seek to an
integral position within the length of the stream.
A type that represents one of the signed basic integral types. It is used to represent the
number of characters transferred in an input/output operation or the size of the input/
output buffers.
The non-standard header <stringfwd> is used for forward declarations of string class
objects.
The template class basic_ios<charT, traits> serves as a base class for class basic_istream
and basic_ostream.
The class ios is an instantiation of basic_ios specialized by the type char.
The class wios is an instantiation of basic_ios specialized by the type wchar_t.
This non-standard header can be used to forward declare basic_string (much like <iosfwd>
forward declares streams). There is also a <stringfwd.h> that forward declares basic_string
and places it into the global namespace.
NOTE
The header <stringfwd> is a non-standard header.
Listing: Header <stringfwd> Synopsis
namespace std { // Optional
template <class T> class allocator;
class basic_string;
string;
typedef basic_string
....
std::string* my_string_ptr;
};
The headers <stringfwd.h> and <string> can be used in combination to place string into the
global namespace, much like is done with other <name.h> headers. The header <string.h>
does not work because that is a standard C header.
Listing: Example of Stringfwd usage
#include <stringfwd.h>
#include <string>
int main()
return 0;
The include header <iostream> declares input and output stream objects. The declared
objects are associated with the standard C streams provided for by the functions in
<cstdio>. This chapter uses the ISO (International Organization for Standardization) C++
Standard as a guide.
The header <iostream> declares standard input and output objects in namespace std.
All streams are buffered (by default) except cerr and wcerr.
NOTE
You can change the buffering characteristic of a stream with:
cout.setf(ios_base::unitbuf);
or
cerr.unsetf(ios_base::unitbuf);
Tip
Do not include <iostream> unless needed. Including and not
using <iostream> will add code size. If you really need it,
consider including only <niostream> instead. This will instantiate
only the narrow console streams, not the wide ones.
Narrow stream objects provide unbuffered input and output associated with standard
input and output declared in <cstdio>.
istream cin;
Remarks
The object cin controls input from an unbuffered stream buffer associated with stdin
declared in <cstdio>. After cin is initialized cin.tie() returns cout.
Returns an istream object.
ostream cout;
Remarks
The object cout controls output to an unbuffered stream buffer associated with stdout
declared in <cstdio>.
ostream cerr;
Remarks
The object cerr controls output to an unbuffered stream buffer associated with stderr
declared in <cstdio>. After err is initialized, err.flags() and unitbuf is nonzero.
ostream clog;
Remarks
The object clog controls output to a stream buffer associated with cerr declared in
<cstdio>.
Wide stream objects provide unbuffered input and output associated with standard input
and output declared in <cstdio>.
wistream wcin;
Remarks
The object wcin controls input from an unbuffered wide stream buffer associated with
stdin declared in <cstdio>. After wcin is initialized wcin.tie() returns wout.
wostream wcout;
Remarks
The object w cout controls output to an unbuffered wide stream buffer associated with
stdout declared in <cstdio>.
wostream wcerr;
Remarks
The object werr controls output to an unbuffered wide stream buffer associated with stderr
declared in <cstdio>. After werr is initialized, werr.flags() and unitbuf is nonzero.
wostream wclog;
Remarks
The object wlog controls output to a wide stream buffer associated with cerr declared in
<cstdio>.
The include header <ios> contains the basic class definitions, types, and enumerations
necessary for input and output stream reading, writing, and other manipulations.
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Header ios
• Typedef Declarations
• Class ios_base
• Template class basic_ios
• ios_base manipulators
The header file <ios> provides for implementation of stream objects for standard input
and output.
The template class fpos<stateT> is a class used for specifying file position information.
The template parameter corresponds to the type needed to hold state information in a
multi-byte sequence (typically mbstate_t from <cwchar>). fpos is essentially a wrapper for
whatever mechanisms are necessary to hold a stream position (and multi-byte state). In
fact the standard stream position typedefs are defined in terms of fpos:
The template class fpos is typically used in the istream and ostream classes in calls
involving file position such as tellg, tellp, seekg and seekp. Though in these classes the
fpos is typedef'd to pos_type, and can be changed to a custom implementation by
specifying a traits class in the stream's template parameters.
16.3.2.1 failure
Remarks
The function failure() constructs a class failure initializing with exception(msg).
16.3.2.2 failure::what
Remarks
The function what() is used to deliver the msg.str().
Returns the message with which the exception was created.
An enumeration used to set various formatting flags for reading and writing of streams.
Init();
Remarks
The default constructor Init() constructs an object of class Init. If init_cnt is zero the
function stores the value one and constructs cin, cout, cerr, clog, wcin, wout, werr and
wlog. In any case the constructor then adds one to init_cnt.
16.3.7.2 Destructor
~Init();
Remarks
The destructor subtracts one from init_cnt and if the result is one calls cout.flush(),
cerr.flush() and clog.flush().
16.3.8.1 flags
Remarks
Use flags() when you would like to use a mask of several flags, or would like to save the
current format configuration. The return value of flags() returns the current fmtflags. The
overloaded flags(fmtflags) alters the format flags but will return the value prior to the
flags being changed.
The fmtflags type before alterations.
See ios enumerators for a list of fmtflags.
SeeAlso:
setiosflags() and resetiosflags()
Listing: Example of flags() usage:
#include <iostream>
// showf() displays flag settings
void showf();
int main()
cin.get();
cout.setf(ios::right|ios::showpoint|ios::fixed);
showf();
return 0;
void showf()
char fflags[][12] = {
"boolalpha",
"dec",
"fixed",
"hex",
"internal",
"left",
"oct",
"right",
"scientific",
"showbase",
"showpoint",
"showpos",
"skipws",
"unitbuf",
"uppercase"
};
if(i & f)
else
Result:
boolalpha is off
dec is on
fixed is off
hex is off
internal is off
left is off
oct is off
right is off
scientific is off
showbase is off
showpoint is off
showpos is off
skipws is on
unitbuf is off
uppercase is off
press enter to continue
boolalpha is off
dec is on
hex is off
internal is off
left is off
oct is off
right is on
scientific is off
showbase is off
showpoint is on
showpos is off
skipws is on
unitbuf is off
uppercase is off
16.3.8.2 setf
fmtflags setf(fmtflags)
fmtflags setf(fmtflags, fmtflags)
Remarks
You should use the function setf() to set the formatting flags for input/output. It is
overloaded. The single argument form of setf() sets the flags in the mask. The two
argument form of setf() clears the flags in the first argument before setting the flags with
the second argument.
type basic_ios::fmtflags is returned.
Listing: Example of setf() usage:
#include <iostream>
int main()
double d = 10.01;
cout.setf(ios::showpos | ios::showpoint);
return 0;
Result:
+10.01
10.01
16.3.8.3 unsetf
void unsetf(fmtflags)
Remarks
Use the unsetf() function to reset any format flags to a previous condition. You would
normally store the return value of setf() in order to achieve this task.
There is no return.
Listing: Example of unsetf() usage:
#include <iostream>
int main()
double d = 10.01;
cout.setf(ios::showpos | ios::showpoint);
cout.unsetf(ios::showpoint);
return 0;
Result:
+10.01
+10.01
16.3.8.4 precision
Remarks
Use the precision() function with floating point numbers to limit the number of digits in
the output. You may use precision() with scientific or non-scientific floating point
numbers. You may use the overloaded precision() to retrieve the current precision that is
set.
With the flag ios::floatfield set, the number in precision refers to the total number of
significant digits generated. If the settings are for either ios::scientific or ios::fixed then
the precision refers to the number of digits after the decimal place.
This means that ios::scientific will have one more significant digit than ios::floatfield,
and ios::fixed will have a varying number of digits.
SeeAlso
setprecision()
int main()
cout.precision(5);
cout.unsetf(ios::floatfield);
cout.setf(ios::scientific, ios::floatfield);
cout.setf(ios::fixed, ios::floatfield);
return 0;
Result:
floatfield: 31.416
scientific: 3.14159e+01
fixed: 31.41593
16.3.8.5 width
Remarks
Use the width() function to set the field size for output. The function is overloaded to
return just the current width setting if there is no parameter or to store and then return the
previous setting before changing the fields width to the new parameter.
Width is the one and only modifier that is not sticky and needs to be reset with each use.
Width is reset to width(0) after each use.
The previous width setting is returned.
Listing: Example of width() usage:
#include <iostream>
int main()
int width;
cout.width(8);
cout.fill('*');
cout.width(width);
return 0;
Result:
Hi!*****
Hi!
Hi!*****
16.3.9.1 imbue
Remarks
The precondition of the argument loc is equal to getloc().
The previous value of getloc().
16.3.9.2 getloc
Remarks
Returns the global C++ locale if no locale has been imbued. Otherwise it returns the
locale of the input and output operations.
16.3.10.1 xalloc
Allocation function.
Remarks
Returns index++.
16.3.10.2 iword
Remarks
If iarray is a null pointer, allocate an array and store a pointer to the first element. The
function extends the array as necessary to include iarray[idx]. Each newly allocated
element of the array is initialized to zero.
The reference returned is invalid after any other operation on the object.
Returns irray[idx]
16.3.10.3 pword
Remarks
If parray is a null pointer, allocates an array of void pointers. Then extends parray as
necessary to include the element parray[idx].
The reference returned is invalid after any other operation on the object.
Returns parray[idx].
16.3.10.4 register_callback
void register_callback
(event_callback fn,
int index);
Remarks
Registers the pai r (fn, index) such that during calls to imbue(),copyfmt() or ~ios_base() the
function fn is called with argument index. Registered functions are called when an event
occurs, in opposite order of registration. Functions registered while a callback function is
active are not called until the next event.
Identical pairs are not merged and a function registered twice will be called twice.
16.3.10.5 sync_with_stdio
Synchronizes stream input output with 'C' input and output functions.
Remarks
Is not supported in the EWL.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 415
Template class basic_ios
Always returns true indicating that the EWL streams are always synchronized with the C
streams.
16.3.11 ios_base
ios_base
protected:
ios_base();
Remarks
The ios_base constructor is protected so it may only be derived from. The values of the
ios_base members are undermined.
~ios_base();
Remarks
Calls registered callbacks and destroys an object of class ios_base.
The basic_ios template class is a base class and includes many enumerations and
mechanisms necessary for input and output operations.
public:
explicit basic_ios
(basic_streambuf<charT,traits>* sb);
protected:
basic_ios();
Remarks
The basic_ios constructor creates an object to class basic_ios and assigns values to its
member functions by calling init().
16.4.2 Destructor
The conditions of the member functions after init() are shown in the following table.
virtual ~basic_ios();
Remarks
Destroys an object of type basic_ios.
16.4.3.1 tie
Remarks
Any stream can have an ostream tied to it to ensure that the ostream is flushed before any
operation. The standard input and output objects cin and cout are tied to ensure that cout
is flushed before any cin operation. The function tie() is overloaded. The parameterless
version returns the current ostream that is tied, if any. The tie() function with an
argument ties the new object to the ostream and returns a pointer, if any, from the first.
The post-condition of tie() function that takes the argument tiestr is that tiestr is equal
to tie();
A pointer to type ostream that is or previously tied, or zero if there was none.
Listing: Example of tie() usage:
// The file EWL-test contains
// CodeWarrior "Software at Work"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
if(!inOut.is_open())
ostream Out(inOut.rdbuf());
if(inOut.tie())
inOut.tie(&Out);
inOut.rdbuf()->pubseekoff(0, ios::end);
if(inOut.tie())
inOut.close();
return 0;
Result:
16.4.3.2 rdbuf
Remarks
To manipulate a stream for random access or synchronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer. The
rdbuf() function that takes an argument has the post-condition of sb is equal to rdbuf().
int number;
char street[40];
} addbook;
int main()
cin.get(addbook.street, 40);
return 0;
Result:
16.4.3.3 imbue
Remarks
The function imbue() calls ios_base::imbue() and
rdbuf->pubimbue().
16.4.3.4 fill
Remarks
Use fill(char_type) in output to fill blank spaces with a character. The function fill() is
overloaded to return the current filler without altering it.
Returns the current character being used as a filler.
SeeAlso
manipulator setfill()
char fill;
cout.width(8);
cout.fill('*');
fill = cout.fill();
return 0;
Result:
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 421
Template class basic_ios
Hi!*****
The filler is a *
16.4.3.5 copyfmt
Remarks
Assigns members of *this object the corresponding objects of the rhs argument with
certain exceptions. The exceptions are rdstate() is unchanged, exceptions() is altered last,
and the contents or pword and iword arrays are copied not the pointers themselves.
Returns the this pointer .
A bool operator.
Remarks
Returns !fail().
16.4.4.2 operator !
A bool not operator.
Remarks
Returns fail().
16.4.4.3 rdstate
Remarks
This member function allows you to read and check the current status of the input and
output formatting flags. The returned value may be stored for use in the function
ios::setstate() to reset the flags at a later date.
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
exit(1);
int count = 0;
int c;
status(in);
status(in);
in.close();
return 0;
int i = in.rdstate();
switch (i) {
break;
break;
break;
break;
Result:
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
Fatal I/O Error
16.4.4.4 clear
void clear
(iostate state = goodbit) throw failure;
Remarks
Use clear() to reset the failbit, eofbit or a badbit that may have been set inadvertently
when you wish to override for continuation of your processing. Post-condition of clear is
the argument and is equal to rdstate().
If rdstate() and exceptions() != 0 an exception is thrown.
No value is returned.
Listing: Example of clear() usage:
// The file ewl-test contains:
// ABCDEFGH
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
exit(1);
int count = 0;
int c;
if(count++ == 4)
in.setstate(ios::failbit);
in.clear();
status(in);
status(in);
in.close();
return 0;
Result:
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
GoodBit set
Non-Fatal I/O Error
16.4.4.5 setstate
Remarks
16.4.4.6 good
Remarks
Use the function good() to test for the lack of error bits being set.
Returns true if rdstate() == 0.
16.4.4.7 eof
Remarks
Use the eof() function to test for an eofbit setting in a stream being processed under some
conditions. This end of file bit is not set by stream opening or closing, but only for
operations that detect an end of file condition.
If eofbit is set in rdstate() true is returned.
Listing: Example of eof() usage
// ewl-test is simply a one line text document
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(TheText);
if(!in.is_open())
exit(1);
int i = 0;
char c;
cout.setf(ios::uppercase);
while(!in.eof())
c = in.get();
cout << c << " " << hex << int(c) << "\n";
if(++i == 5) in.setstate(ios::eofbit);
return 0;
Result:
A 41
B 42
C 43
D 44
E 45
16.4.4.8 fail
Remarks
The member function fail() will test for failbit and badbit.
Returns true if failbit or badbit is set in rdstate().
Listing: Example of fail() usage
// ewl-test file for input contains.
// float 33.33 double 3.16e+10 Integer 789 character C
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
char ch = 0;
while(!in.fail())
if(ch)cout.put(ch);
in.get(ch);
return 0;
Result:
16.4.4.9 bad
Remarks
Use the member function bad() to test if a fatal input or output error occurred which sets
the badbit flag in the stream.
Returns true if badbit is set in rdstate().
SeeAlso
basic_ios::fail()
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
exit(1);
int count = 0;
int c;
if(count++ == 4) in.setstate(ios::failbit);
status(in);
status(in);
return 0;
Result:
GoodBit set
GoodBit set
GoodBit set
GoodBit set
Non-Fatal I/O Error
Non-Fatal I/O Error
16.4.4.10 exceptions
Remarks
The function exceptions() determines what elements in rdstate() cause exceptions to be
thrown. The overloaded exceptions(iostate) calls clear(rdstate()) and leaves the argument
except equal to exceptions().
Manipulators are used in the stream to alter the formatting of the stream.
A reference to an object of type ios_base is returned to the stream. (The this pointer.)
#include <iostream>
#include <iomanip>
int main()
return 0;
Result:
Original Number is 64
Hexadecimal : 0x40
Octal :0100
Decimal : 64
Remarks
Use overloaded manipulators to provide specific and unique formatting methods relative
to one class.
A reference to ostream. (Usually the this pointer.)
See Also
<iomanip> for manipulators with parameters
Listing: Example of overloaded manipulator usage:
#include <iostream>
using namespace std;
ostream &rJus(ostream &stream);
int main()
{
cout << "align right " << rJus << "for column";
return 0;
}
Result:
align right for column
The header <streambuf> defines types that control input and output to character sequences.
Listing: Header <streambuf>
namespace std {
template <class charT, class traits = char_traits<charT> >
class basic_streambuf;
This chapter is constructed in the following sub sections and uses the ISO (International
Organization for Standardization) C++ Standard as a guide:
• Stream buffer requirements
• Class basic_streambuf
There are three pointers that control the operations performed on a sequence or associated
sequences. These are used for read, writes and stream position alteration. If not null all
pointers point to the same charT array object.
• The beginning pointer or lowest element in an array. - ( beg)
• The next pointer of next element addressed for read or write. - ( next)
• The end pointer of first element addressed beyond the end of the array. - ( end)
The template class basic_streambuf is an abstract class for deriving various stream buffers
whose objects control input and output sequences.
The type streambuf is an instantiation of char type. the type wstreambuf is an instantiation of
wchar_t type.
protected:
basic_streambuf();
Remarks
The constructor sets all pointer member objects to null pointers and calls getloc() to copy
the global locale at the time of construction.
17.2.1.1 Destructor
virtual ~basic_streambuf();
Remarks
Removes the object from memory.
The public member functions allow access to member functions from derived classes.
17.2.2.1 Locales
Locales are used for encapsulation and manipulation of information to a particular locale.
17.2.2.2 basic_streambuf::pubimbue
Remarks
The function pubimbue calls imbue(loc).
Returns the previous value of getloc().
17.2.2.3 basic_streambuf::getloc
Remarks
If pubimbue has already been called, it returns the last value of loc supplied; otherwise the
current one. If pubimbue has been called but has not returned a value from imbue, it then
returns the previous value.
17.2.3.1 basic_streambuf::pubsetbuf
Remarks
The first argument is used in an another function by a filebuf derived class. See setbuf().
The second argument is used to set the size of a dynamic allocated buffer.
Returns a pointer to basic_streambuf<char_type, traits> via setbuf(s, n).
int main()
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("CodeWarrior",50);
strbuf.sgetn(temp, 50);
return 0;
Result:
CodeWarrior
17.2.3.2 basic_streambuf::pubseekoff
(off_type off,
Remarks
The member function pubseekoff() is used to find the difference in bytes of the get pointer
from a known position (such as the beginning or end of a stream). The function
pubseekoff() returns a type pos_type which holds all the necessary information.
See Also
pubseekpos()
#include <iostream>
#include <fstream>
#include <stdlib.h>
char inFile[] = "ewl-test";
ostream Out(inOut.rdbuf());
char str[] = "\nRegistered Trademark";
inOut.rdbuf()->pubseekoff(0, ios::end);
Out << str;
inOut.close();
return 0;
}
Result:
The File now reads:
CodeWarrior "Software at Work"
Registered Trademark
17.2.3.3 basic_streambuf::pubseekpos
(pos_type sp,
Remarks
The function pubseekpos() is use to move to a desired offset using a type pos_type, which
holds all necessary information.
Returns a pos_type via seekpos(sb, which)
See Also
pubseekoff(), seekoff()
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in("ewl-test");
if(!in.is_open())
{cout << "could not open file"; exit(1);}
streampos spEnd(0), spStart(0), aCheck(0);
spEnd = spStart = 5;
char ch;
while(spEnd != spStart+10)
{
in.get(ch);
cout << ch;
spEnd = in.rdbuf()->pubseekoff(0, ios::cur);
}
aCheck = in.rdbuf()->pubseekoff(0,ios::cur);
cout << "\nThe final position's offset"
<< " in bytes now is "
<< static_cast<streamoff>(aCheck) << endl;
in.close();
return 0;
}
Result:
The offfset for the start of the reading in bytes is 5
FGHIJKLMNO
The final position's offset in bytes now is 15
17.2.3.4 basic_streambuf::pubsync
int pubsync();
Remarks
The function pubsync() will attempt to synchronize the streambuf input and output.
Returns zero if successful or EOF if not via sync().
Listing: Example of streambuf::pubsync() usage:
#include <iostream>
struct address {
int number;
char street[40];
}addbook;
int main()
cin.get(addbook.street, 40);
return 0;
Result:
17.2.4.1 basic_streambuf::in_avail
streamsize in_avail();
Remarks
If a read is permitted returns size of stream as a type streamsize.
17.2.4.2 basic_streambuf::snextc
int_type snextc();
Remarks
The function snextc() calls sbumpc() to extract the next character in a stream. After the
operation, the get pointer references the character following the last character extracted.
If sbumpc returns traits::eof, otherwise returns sgetc().
Listing: Example of streambuf::snextc() usage:
#include <iostream>
#include <sstream>
int main()
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("ABCDE",50);
char ch;
ch =strbuf.snextc();
ch = strbuf.snextc();
return 0;
Result:
BC
17.2.4.3 basic_streambuf::sbumpc
Remarks
The function sbumpc() moves the get pointer one element when called.
Return
The value of the character at the get pointer. It returns uflow() if it fails to move the
pointer.
See Also
sgetc()
int main()
{
using namespace std;
stringbuf strbuf(buf);
int ch;
for (int i = 0; i < 23; i++)
{
ch = strbuf.sgetc();
strbuf.sbumpc();
cout.put(ch);
}
Result:
CodeWarrior
CodeWarrior --Software at Work--
17.2.4.4 basic_streambuf::sgetc
int_type sgetc();
Remarks
The function sgetc() extracts a single character, without moving the get pointer.
A int_type type at the get pointer if available, otherwise returns underflow().
For an example of streambuf::sgetc() usage refer to streambuf::sbumpc()
17.2.4.5 basic_streambuf::sgetn
Remarks
The public member function sgetn() is used to extract a series of characters from the
stream buffer. After the operation, the get pointer references the character following the
last character extracted.
Returns a streamsize type as returned from the function xsgetn(s,n).
For an example of streambuf::sgetn() usage refer to pubsetbuf()
17.2.5 Putback
17.2.5.1 basic_streambuf::sputbackc
Remarks
The function sputbackc() will replace a character extracted from the stream with another
character. The results are not assured if the putback is not immediately done or a different
character is used.
If successful, returns a pointer to the get pointer as an int_type otherwise returns
pbackfail(c).
int main()
stringbuf strbuf(buffer);
char ch;
ch = strbuf.snextc();
strbuf.pubseekoff(0, ios::beg);
return 0;
Result:
AxBC
xBCDEF
17.2.5.2 basic_streambuf::sungetc
int_type sungetc();
Remarks
The function sungetc() restores the previously extracted character. After the operation, the
get pointer references the last character extracted.
If successful, returns a pointer to the get pointer as an int_type otherwise returns
pbackfail(c).
17.2.6.1 basic_streambuf::sputc
Remarks
The function sputc() inserts a character into the stream. After the operation, the get
pointer references the character following the last character inserted.
If successful, returns c as an int_type otherwise returns overflow(c).
Listing: Example of streambuf::sputc() usage:
#include <iostream>
#include <sstream>
int main()
stringbuf strbuf;
strbuf.sputc('A');
char ch;
ch = strbuf.sgetc();
return 0;
Result:
17.2.6.2 basic_streambuf::sputn
Remarks
The function sputn() inserts a series of characters into a stream. After the operation, the
get pointer references the character following the last character inserted.
Returns a streamsize type returned from a call to xputn(s,n).
Protected member functions that are used for stream buffer manipulations by the
basic_streambuf class and derived classes from it.
17.2.7.1 basic_streambuf::eback
Remarks
Returns the beginning pointer.
17.2.7.2 basic_streambuf::gptr
Remarks
Returns the next pointer.
17.2.7.3 basic_streambuf::egptr
Remarks
Returns the end pointer.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 451
Class basic_streambuf
17.2.7.4 basic_streambuf::gbump
Remarks
The function gbump() advances the input pointer by the value of the int n argument.
17.2.7.5 basic_streambuf::setg
void setg
(char_type *gbeg,
char_type *gnext,
char_type *gend);
Remarks
After the call to setg() the gbeg pointer equals eback(), the gnext pointer equals gptr(),
and the gend pointer equals egptr().
17.2.8.1 basic_streambuf::pbase
Remarks
17.2.8.2 basic_streambuf::pptr
Remarks
Returns the next pointer.
17.2.8.3 basic_streambuf::epptr
Remarks
Returns the end pointer.
17.2.8.4 basic_streambuf::pbump
Remarks
The function pbump() advances the next pointer by the value of the int argument n.
17.2.8.5 basic_streambuf::setp
To set the values for the beginning, next and end pointers.
void setp
(char_type* pbeg,
char_type* pend);
Remarks
After the call to setp(), pbeg equals pbase(), pbeg equals pptr() and pend equals epptr().
The virtual functions in basic_streambuf class are to be overloaded in any derived class.
17.2.9.1 Locales
To get and set the stream locale. These functions should be overridden in derived classes.
17.2.9.2 basic_streambuf::imbue
Remarks
The imbue() function allows the derived class to be informed in changes of locale and to
cache results of calls to locale functions.
Virtual functions for positioning and manipulating the stream buffer. These functions
should be overridden in derived classes.
17.2.10.1 basic_streambuf::setbuf
Remarks
The function setbuf() is overridden in basic_stringbuf and basic_filebuf classes.
Returns the this pointer.
17.2.10.2 basic_streambuf::seekoff
Remarks
The function seekoff() is overridden in basic_stringbuf and basic_filebuf classes.
Returns a pos_type value, which is an invalid stream position.
17.2.10.3 basic_streambuf::seekpos
Remarks
The function seekpos() is overridden in basic_stringbuf and basic_filebuf classes.
Returns a pos_type value, which is an invalid stream position.
17.2.10.4 basic_streambuf::sync
Remarks
If pbase() is non null the characters between pbase() and pptr() are written to the control
sequence. The function setbuf() overrides the basic_filebuf class.
Returns zero if successful and -1 if failure occurs.
17.2.11.1 basic_streambuf::showmanyc
Remarks
The function returns zero for the default behavior. Derived classes may return a negative
one or a non-negative value. A positive value estimates the number of characters
available in the sequence. If a positive value is returned, then successive calls to
underflow() will not return traits::eof() until at least that number of characters have been
extracted from the stream. If showmanyc() returns -1, then calls to underflow() or uflow()
will fail.
Note that underflow or uflow might fail by throwing an exception prematurely. The
intention is that the calls will not return eof() and will return immediately.
17.2.11.2 basic_streambuf::xsgetn
Remarks
The characters are read by repeated calls to sbumpc() until either n characters have been
assigned or EOF is encountered.
Returns the number of characters read.
17.2.11.3 basic_streambuf::underflow
Remarks
The function underflow() is called when a character is not available for sgetc().
There are many constraints for underflow().
The pending sequence of characters is a concatenation of end pointer minus the get
pointer plus some sequence of characters to be read from input.
The result character if the sequence is not empty, the first character in the sequence or the
next character in the sequence.
The backup sequence if the beginning pointer is null, the sequence is empty, otherwise
the sequence is the get pointer minus the beginning pointer.
Returns the first character of the pending sequence and does not increment the get
pointer. If the position is null returns traits::eof() to indicate failure.
17.2.11.4 basic_streambuf::uflow
To show a underflow condition for a single character and increment the get pointer.
Remarks
The function uflow() is called when a character is not available for sbumpc().
The constraints are the same as underflow(), with the exceptions that the resultant
character is transferred from the pending sequence to the back up sequence and the
pending sequence may not be empty.
Calls underflow() and if traits::eof is not returned returns the integer value of the get
pointer and increments the next pointer for input.
17.2.12 Putback
Virtual functions for replacing data to a stream. These functions should be overridden in
derived classes.
17.2.12.1 basic_streambuf::pbackfail
Remarks
The resulting conditions are the same as the function underflow().
The function pbackfail() is only called when a put back operation really has failed and
returns traits::eof. If success occurs the return is undefined.
17.2.13.1 basic_streambuf::xsputn
Remarks
The function xsputn() writes to the output character by using repeated calls to sputc(c).
Write stops when n characters have been written or EOF is encountered.
Returns the number of characters written in a type streamsize.
17.2.13.2 basic_streambuf::overflow
Remarks
The pending sequence is defined as the concatenation of the put pointer minus the
beginning pointer plus either the sequence of characters or an empty sequence, unless the
beginning pointer is null in which case the pending sequence is an empty sequence.
This function is called by sputc() and sputn() when the buffer is not large enough to hold
the output sequence.
Overriding this function requires that:
When overridden by a derived class how characters are consumed must be specified.
After the overflow either the beginning pointer must be null or the beginning and put
pointer must both be set to the same non-null value.
The function may fail if appending characters to an output stream fails or failure to set the
previous requirement occurs.
The function returns traits::eof() for failure or some unspecified result to indicate
success.
18.1 Headers
This section lists the header for istream, ostream, and iomanip.
A class that defines several functions for stream input mechanisms from a controlled
stream buffer.
The basic_istream class is derived from the basic_ios class and provides many functions
for input operations.
explicit basic_istream
(basic_streambuf<charT, traits>* sb);
Remarks
The basic_istream constructor is overloaded. It can be created as a base class with no
arguments. It may be a simple input class initialized to a previous object's stream buffer.
18.2.1.2 Destructor
virtual ~basic_istream()
Remarks
The basic_istream destructor removes from memory the basic_istream object.
Listing: Example of basic_istream() usage:
// ewl-test file contains
// Ask the teacher anything you want to know
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
if(!out.is_open())
istream inOut(out.rdbuf());
char c;
while(inOut.get(c)) cout.put(c);
return 0;
Result:
explicit sentry
(basic_istream<charT, traits>& is, bool noskipws = false);
Remarks
If after the operation is.good() is true ok_ equals true otherwise ok_ equals false. The
constructor may call setstate(failbit) which may throw an exception.
18.2.2.2 Destructor
Destroys a sentry object.
~sentry();
Remarks
The destructor has no effects.
operator bool();
Remarks
Operator bool returns the value of ok_
Extractors that provide formatted arithmetic input operations. Each signature extracts the
specified type and stores it in n.
Remarks
The Arithmetic extractors extract a specific type from the input stream and store it in the
address provided.
Table 18-1. States and stdio equivalents
state stdio equivalent
(flags() & basefield) == oct %o
(flags() & basefield) == hex %x
(flags() & basefield) != 0 %x
(flags() & basefield) == 0 %i
Otherwise
signed integral type %d
unsigned integral type %u
(basic_istream<charT,traits>&))
Returns pf(*this).
Remarks
The various overloaded extractors are used to obtain formatted input dependent upon the
type of argument. Since they return a reference to the calling stream they may be chained
in a series of extractions. The overloaded extractors work "as if" like fscanf() in standard
C and read until a white space character or EOF is encountered.
The white space character is not extracted and is not discarded, but simply ignored. Be
careful when mixing unformatted input operations with the formatted extractor operators,
such as when using console input.
The this pointer is returned.
See Also
basic_ostream::operator
Listing: Example of basic_istream:: extractor usage:
// The ewl-test input file contains
// float 33.33 double 3.16e+10 Integer 789 character C
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in(ioFile);
if(!in.is_open())
{cout << "cannot open file for input"; exit(1);}
cin >> i;
cout << "Enter a word: ";
in.close();
return 0;
}
Result:
float 33.33
double 3.16e+10
Integer 789
character C
extractor prototype
Basic_istream &operator >>(basic_istream &s,const imanip<T>&)
{ // procedures
return s;
}
Remarks
You may overload the extractor operator to tailor the specific needs of a particular class.
The this pointer is returned.
#include <cstdlib>
#include <cstring>
class phonebook {
phonebook o);
phonebook &o);
private:
char name[80];
int areacode;
int exchange;
int num;
public:
};
int main()
phonebook a;
cin >> a;
cout << a;
return 0;
return stream;
char buf[5];
o.num = atoi(buf);
return stream;
Result:
NOTE
Older versions of the library may begin by calling ipfx() and
end by calling isfx() and returning the value specified.
18.2.4.1 basic_istream::gcount
Remarks
Use the function gcount() to obtain the number of bytes read by the last unformatted input
function called by that object.
Returns an int type count of the bytes read.
Listing: Example of basic_istream::gcount() usage:
#include <iostream>
#include <fstream>
const SIZE = 4;
struct stArray {
int index;
double dNum;
};
int main()
ofstream fOut("test");
if(!fOut.is_open())
stArray arr;
short i;
arr.index = i;
arr.dNum = i *3.14;
fOut.close();
stArray aIn[SIZE];
ifstream fIn("test");
if(!fIn.is_open())
count+=fIn.gcount();
cout << count << " bytes read " << endl;
<< endl;
fIn.close();
return 0;
Result:
48 bytes read
The size of the structure is 12
1 3.14
2 6.28
3 9.42
4 12.56
18.2.4.2 basic_istream::get
int_type get();
Extracts a character if available and returns that value, otherwise calls setstate(failbit)
and returns eof().
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 471
Input Streams
18.2.4.2.1 Remarks
Extracts characters and stores them in a char array at an address pointed to by s, until:
• a limit (the second argument minus one) or the number of characters to be stored is
reached
• a delimiter (the default value is the newline character) is met. In which case, the
delimiter is not extracted.
If end_of_file is encountered, setstate(eofbit) is called.
If no characters are extracted setstate(failbit)is called. In any case, it stores a null
character in the next available location of array s.
Extracts characters and assigns them to the basic_streambuf object sb if possible or else it
calls setstate(failbit). Extraction stops if:
• an insertion fails
• end-of-file is encountered
• an exception is thrown
Returns an integer when used with no argument. When used with an argument, if a
character is extracted, the get() function returns the this pointer. If no character is
extracted setstate(failbit) is called. In any case a null char is appended to the array.
See Also
basic_istream::getline
Listing: Examples of basic_istream::get() usage:
// READ ONE CHARACTER:
// ewl-test file for input
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
char ch;
return 0;
#include <iostream>
const int size = 100;
char buf[size];
int main()
{
using namespace std;
cout << " Enter your name: ";
cin.get(buf, size);
cout << buf;
return 0;
}
Result:
18.2.4.3 basic_istream::getline
Remarks
The unformatted getline() function retrieves character input, and stores it in a character
array buffer s if possible until the following conditions evaluated in this order occur. If no
characters are extracted setstate(failbit) is called.
end-of-file occurs in which case setstate(eofbit) is called.
A delimiter (default value is the newline character) is encountered. In which case the
delimiter is read and extracted but not stored.
A limit (the second argument minus one) is read.
If n-1 chars are read, that failbit gets set.
In any case it stores a null char into the next successive location of the array.
The this pointer is returned.
See Also
basic_ostream::flush
Listing: Example of basic_istream::getline() usage:
#include <iostream>
const int size = 120;
int main()
{
using namespace std;
char compiler[size];
cout << "Enter your compiler: ";
cin.getline(compiler, size);
cout << "You use " << compiler;
return 0;
}
Result:
#include <iostream>
const int size = 120;
int main()
{
using namespace std;
cout << "What kind of Compiler do you use: ";
char compiler[size];
cin.getline(compiler, size,TAB);
cout << compiler;
cout << "\nsecond input not needed\n";
cin >> compiler;
cout << compiler;
return 0;
}
Result:
What kind of Compiler do you use:
CodeWarrior<tab>Why?
CodeWarrior
Why?
18.2.4.4 basic_istream::ignore
Remarks
The function ignore() will extract and discard characters until:
• a limit is met (the first argument)
• end-of-file is encountered (in which case setstate(eofbit) is called)
The next character c is equal to the delimiter delim, in which case it is extracted except
when c is equal to traits::eof();
The this pointer is returned.
Listing: Example of basic_istream::ignore() usage:
// The file ewl-test contains:
// char ch; // to save char
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
char ch;
in.ignore(100, '\n');
return 0;
Result:
char ch;
/*This C comment will remain */
while((ch = in.get())!= EOF) cout.put(ch);
/* the C++ comments won't */
18.2.4.5 basic_istream::peek
Remarks
The function peek() allows you to look ahead at the next character in a stream to be
extracted without extracting it.
If good() is false returns traits::eof() else returns the value of the next character in the
stream.
See Also
18.2.4.6 basic_istream::read
Remarks
The function read() will attempt to extract a block of binary data until the following
conditions are met.
A limit of n number of characters are stored.
end-of-file is encountered on the input (in which case setstate(failbit) is called.
Return
The this pointer is returned.
SeeAlso
basic_ostream::write
Listing: Example of basic_istream::read() usage:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
struct stock {
char name[80];
double price;
long trades;
};
int main()
strcpy(Opening.name, Company);
Opening.price = 180.25;
Opening.trades = 581300;
if(!Market.is_open())
Market.close();
if(!Market2.is_open())
<< "The number of trades was: " << Closing.trades << '\n';
<< "The closing price is: $" << Closing.price << endl;
Market2.close();
return 0;
Result:
18.2.4.7 basic_istream::readsome
streamsize readsome
(charT_type* s, streamsize n);
Remarks
The function readsome extracts and stores characters in the buffer pointed to by s until the
following conditions are met.
• end-of-file is encountered (in which case setstate(eofbit) is called.)
• no characters are extracted
• a limit of characters is extracted; either n or the size of the buffer.
Return
The number of characters extracted.
Listing: Example of basic_istream::readsome() usage.
The file ewl-test contains:
CodeWarrior
Software at Work
Registered Trademark
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
const short SIZE = 81;
int main()
{
using namespace std;
ifstream in("ewl-test");
if(!in.is_open())
{cout << "can't open file for input"; exit(1);}
char Buffer[SIZE] = "\0";
ostringstream Paragraph;
while(in.good() && (in.peek() != EOF))
{
in.readsome(Buffer, 5);
Paragraph << Buffer;
}
cout << Paragraph.str();
in.close();
return 0;
}
Result:
CodeWarrior
Software at Work
Registered Trademark
18.2.4.8 basic_istream::putback
(char_type c);
Remarks
The function putback() allows you to replace the last character extracted by calling
rdbuf()->sungetc(). If the buffer is empty, or if sungetc() returns eof, setstate(failbit) may
be called.
Return
The this pointer is returned.
See Also
basic_istream::unget
Listing: Example of basic_istream::putback usage:
// The file ewl-test contains.
char ch; // to save char
/* comment will remain */
while((ch = in.get())!= EOF) cout.put(ch);
// read until failure
#include <iostream>
#include <fstream>
#include <stdlib.h>
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "file not opened"; exit(1);}
Result:
char ch; // to save char
/* comment will remain */
while((ch = in.get())!= EOF) cout.put(ch);
read until failure
18.2.4.9 basic_istream::unget
Remarks
Use the function unget() to return the previously extracted character. If rdbuf() is null or if
end-of-file is encountered setstate(badbit) is called.
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in(inFile);
if(!in.is_open())
{cout << "file not opened"; exit(1);}
char ch, tmp;
while((ch = in.get()) != EOF)
{
if(ch == bslash)
{
in.get(tmp);
if(tmp != bslash)
in.unget();
else continue;
}
cout << ch;
}
Result:
char ch; // to save char
/* comment will remain */
// read until failure
while((ch = in.get()) != EOF) cout.put(ch);
18.2.4.10 basic_istream::sync
int sync();
Remarks
This function attempts to make the input source consistent with the stream being
extracted.
If rdbuf()->pubsync() returns -1 setstate(badbit) is called and traits::eof is returned.
Return
If rdbuf() is Null returns -1 otherwise returns zero.
Listing: Example of basic_istream::sync() usage:
// The file ewl-test contains:
// This functions attempts to make the input source
// --
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFile);
if(!in.is_open())
char str[10];
while (in.good())
cout <<str;
return 0;
Result:
18.2.4.11 basic_istream::tellg
Remarks
The function tellg calls rdbuf()->pubseekoff(0, cur, in).
18.2.4.12 basic_istream::seekg
Remarks
The function seekg is overloaded to take a pos_type object, or an off_type object (defined
in basic_ios class.) The function is used to set the position of the get pointer of a stream
to a random location for character extraction.
The this pointer is returned.
See Also
basic_streambuf::pubseekoff() and pubseekpos().
Listing: Example of basic_istream::seekg() usage:
// The file ewl-test contains:
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in("ewl-test");
if(!in.is_open())
{cout << "could not open file"; exit(1);}
char ch;
while(spEnd != spStart+10)
{
in.get(ch);
cout << ch;
spEnd = in.tellg();
}
aCheck = in.tellg();
cout << "\nThe current position's offset in bytes now is "
<< aCheck << endl;
streamoff gSet = 0;
in.seekg(gSet, ios::beg);
aCheck = in.tellg();
cout << "The final position's offset in bytes now is "
<< aCheck << endl;
in.close();
return 0;
}
Result:
18.2.5.1 basic_ifstream::ws
Remarks
The ws manipulator skips whitespace characters in input.
The this pointer is returned.
Listing: Example of basic_istream:: manipulator ws usage:
// The file ewl-test (where the number of blanks (and/or tabs)
// is unknown) contains:
// a b c
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
ifstream in(inFileName);
if (!in.is_open())
char ch;
in.unsetf(ios::skipws);
while (1)
if (in.good())
else break;
in.clear();
in.seekg(0, ios::beg);
while (1)
if (in.good())
else break;
in.close();
return(0);
Result:
Remarks
Calls basic_istream(<charT, traits>(sb) and basic_ostream(charT, traits>(sb). After it is
constructed rdbuf() equals sb and gcount() equals zero.
18.2.5.2.1 Destructor
virtual ~basic_iostream();
Remarks
Destroys an object of type basic_iostream.
The basic_ostream class provides for output stream mechanisms for output stream
classes. The basic_ostream class may be used as an independent class, as a base class for
the basic_ofstream class or a user derived class.
explicit basic_ostream(basic_streambuf<char_type,
traits>*sb);
Remarks
The basic_ostream constructor constructs and initializes the base class object.
18.3.1.2 Destructor
virtual ~basic_ostream();
Remarks
Removes a basic_ostream object from memory.
Listing: Example of basic_ostream() usage:
// The ewl-test file contains originally
// CodeWarrior "Software at Work"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
if(!inOut.is_open())
ostream Out(inOut.rdbuf());
inOut.rdbuf()->pubseekoff(0, ios::end);
inOut.close();
return 0;
Result:
Remarks
If after the operation os.good() is true ok_ equals true otherwise ok_ equals false. The
constructor may call setstate(failbit) which may throw an exception.
18.3.2.2 Destructor
~sentry();
Remarks
The destructor under normal circumstances will call os.flush().
operator bool();
Remarks
Operator bool returns the value of ok_
Remarks
Converts an arithmetic value. The formatted values are converted as if they had the same
behavior of the fprintf() function.
In most cases *this is returned unless failure, in which case set state(failbit) is called.
Table 18-2. Output states and stdio equivalents.
Output State stdio equivalent
Integers
(flags() & basefield) == oct %o
(flags() & basefield) == hex %x
(flags() & basefield) != 0 %x
Otherwise
signed integral type %d
unsigned integral type %u
Floating Point Numbers
(flags() & floatfield) == fixed %f
(flags() & floatfield) == scientific (flags() & uppercase) != 0 %e %E
Otherwise
(flags() & uppercase) != 0 %g %G
An integral type other than a char type
(flags() & showpos) != 0 (flags() & showbase) != 0 +#
A floating point type
(flags() & showpos) != 0 (flags() & showpoint) != 0 +#
For any conversion, if width() is non-zero then a field with a conversion specification has
the value of width().
For any conversion, if (flags() and fixed) !=0 or if precision() >0 the conversion
specification is the value of precision().
For any conversion, padding behaves in the following manner.
Table 18-3. Conversion state and stdio equivalents
State Justification stdio equivalent
(flags()& adjustfield) == left left space padding
(flags() & adjustfield) == internal Internal zero padding
Otherwise right space padding
The ostream insertion operators are overloaded to provide for insertion of most predefined
types into an output stream. They return a reference to the basic stream object so they may
be used in a chain of statements to input various types to the same stream.
18.3.3.3 basic_ostream::operator<<
Returns pf(*this).
Converts the pointer to void p as if the specifier was %p and returns *this.
If sb is null calls setstate(failbit) otherwise gets characters from sb and inserts them into
*this until:
• end-of-file occurs
• inserting into the stream fails
• an exception is thrown.
If the operation fails, it calls setstate(failbit) or re-throws the exception, otherwise
returns *this.
Remarks
The formatted output functions insert the values into the appropriate argument type.
Most inserters (unless noted otherwise) return the this pointer.
Listing: Example of basic_ostream inserter usage:
#include <cstdlib>
int main()
ofstream out(oFile);
out.close();
return 0;
Result:
Output: to ewl-test
float 33.33 double 3.16e+10 Integer 789 character C
Output to console
float 33.33
double 3.16e+10
Integer 789
character C
Overloading
inserter prototype
basic_ostream &oerator<<
(basic_ostream &stream,const omanip<T>&){
// procedures;
return stream;
}
Remarks
You may overload the inserter operator to tailor it to the specific needs of a particular
class.
The this pointer is returned.
Listing: Example of overloaded inserter usage:
#include <iostream>
#include <string.h>
#include <iomanip>
class phonebook {
protected:
char *name;
int areacode;
int exchange;
int num;
public:
areacode(a),
exchange(p),
num(nm),
name(n) {}
};
int main()
return 0;
return stream;
Result:
18.3.4.1 basic_ostream::tellp
Return
If f ail() returns -1 else returns rdbuf()->pubseekoff(0, cur, out).
See Also
basic_istream::tellg, basic_ostream::seekp
Example of basic_ostream::tellp() usage see basic_ostream::seekp
18.3.4.2 basic_ostream::seekp
(off_type, iosbase::seekdir);
Remarks
The function seekp is overloaded to take a single argument of a pos_type pos that calls
rdbuf()->pubseekpos(pos). It is also overloaded to take two arguments: an off_type off and i
os_base::seekdir type dir that calls rdbuf()->pubseekoff(off, dir).
int main()
{
using namespace std;
ostringstream ostr(motto);
streampos cur_pos, start_pos;
cout << "The original array was :\n"
<< motto << "\n\n";
// associate buffer
stringbuf *strbuf(ostr.rdbuf());
streamoff str_off = 10;
cur_pos = ostr.tellp();
cout << "The current position is "
<< cur_pos.offset()
<< " from the beginning\n";
ostr.seekp(str_off);
cur_pos = ostr.tellp();
cout << "The current position is "
<< cur_pos.offset()
<< " from the beginning\n";
strbuf->sputc('\0');
cout << "The stringbuf array is\n"
<< strbuf->str() << "\n\n";
cout << "The ostringstream array is still\n"
<< motto;
return 0;
}
Results:
The original array was :
CodeWarrior
18.3.4.3 basic_ostream::put
Remarks
The unformatted function put() inserts one character in the output stream. If the operation
fails, it calls setstate(badbit).
The this pointer is returned.
Listing: Example of basic_ostream::put() usage:
#include <iostream>
int main()
while(*str)
cout.put(*str++);
return 0;
Result:
18.3.4.4 basic_ostream::write
Remarks
The overloaded function write() is used to insert a block of binary data into a stream. This
function can be used to write an object by casting that object as a unsigned char pointer.
If the operation fails, setstate(badbit) is called.
A reference to ostream. The this pointer is returned.
SeeAlso
basic_istream::read
Listing: Example of basic_ostream::write() usage:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
struct stock {
char name[80];
double price;
long trades;
};
int main()
{
using namespace std;
stock Opening, Closing;
strcpy(Opening.name, Company);
Opening.price = 180.25;
Opening.trades = 581300;
if(!Market.is_open())
{cout << "can't open file for output"; exit(1);}
if(!Market2.is_open())
{cout << "can't open file for input"; exit(2);}
Market2.close();
return 0;
}
Result:
Big Bucks Inc.
18.3.4.5 basic_ostream::flush
Remarks
The function flush() is an output only function in C++. You may use it for an immediate
expulsion of the output buffer. This is useful when you have critical data or you need to
ensure that a sequence of events occurs in a particular order. If the operation fails, it calls
setstate(badbit).
#include <ctime>
class stopwatch {
private:
public:
stopwatch();
~stopwatch();
void start();
void stop();
};
stopwatch::stopwatch()
end = 0.0;
start();
stopwatch::~stopwatch()
void stopwatch::start()
set = double(clock()/CLOCKS_PER_SEC);
void stopwatch::stop()
end = double(clock()/CLOCKS_PER_SEC);
int main()
time_delay(5);
time(&tStart);
Result:
Remarks
The manipulator endl takes no external arguments, but is placed in the stream. It inserts a
newline character into the stream and flushes the output.
18.3.5.2 basic_ostream::ends
Remarks
The manipulator ends, takes no external arguments, but is placed in the stream. It inserts
a NULL character into the stream, usually to terminate a string.
A reference to ostream. The this pointer is returned.
The ostringstream provides in-core character streams but must be null terminated by the
user. The manipulator ends provides a null terminator.
Listing: Example of basic_ostream:: ends usage:
#include <iostream>
#include <sstream>
int main()
out << 2 << " plus " << 2 << " equals "
return 0;
Result:
18.3.5.3 basic_ostream::flush
Remarks
The manipulator flush, takes no external arguments, but is placed in the stream. The
manipulator flush will attempt to release an output buffer for immediate use without
waiting for an external input.
A reference to ostream. The this pointer is returned.
Note in the Example of basic_ostream:: flush usage: comment out the flush and both lines
will display simultaneously at the end of the program.
See Also
basic_ostream::flush
Listing: Example of basic_ostream:: flush usage:
#include <iostream>
#include <iomanip>
#include <ctime>
class stopwatch {
private:
double begin, set, end;
public:
stopwatch();
~stopwatch();
void start();
void stop();
};
stopwatch::stopwatch()
{
using namespace std;
begin = (double) clock() / CLOCKS_PER_SEC;
end = 0.0;
start();
{
begin = (double) clock() / CLOCKS_PER_SEC;
end = 0.0;
start();
cout << "begin time the timer: " << flush;
}
stopwatch::~stopwatch()
{
using namespace std;
stop(); // set end
cout << "\nThe Object lasted: ";
cout << fixed << setprecision(2)
<< end - begin << " seconds \n";
}
void stopwatch::stop()
{
using namespace std;
end = double(clock()/CLOCKS_PER_SEC);
}
int main()
{
using namespace std;
stopwatch watch; // create object and initialize
time_delay(5);
return 0; // destructor called at return
}
Results:
begin time the timer:
< short pause >
The Object lasted: 3.78 seconds
18.4.2 resetiosflags
Remarks
Use the manipulator resetiosflags directly in a stream to reset any format flags to a
previous condition. You would normally store the return value of setf() in order to
achieve this task.
A smanip type is returned, which is an implementation defined type.
See Also
ios_base::setf(), ios_base::unsetf()
int main()
{
using namespace std;
double d = 2933.51;
long flags;
flags = ios::scientific | ios::showpos | ios::showpoint;
Result:
Original: 2933.51
18.4.3 setiosflags
Remarks
Use the manipulator setiosflags() to set the input and output formatting flags directly in
the stream.
A smanip type is returned, which is an implementation defined type.
See Also
ios_base::setf(), ios_base::unsetf()
18.4.4 setbase
Remarks
The manipulator setbase() directly sets the numeric base of integral output to the stream.
The arguments are in the form of 8, 10, 16, or 0, and 8 octal, 10 decimal and 16
hexadecimal. Zero represents ios::basefield; a combination of all three.
Returns a smanip type, which is an implementation defined type.
See Also
ios_base::setf()
int main()
{
using namespace std;
cout << "Hexadecimal "
<< setbase(16) << 196 << '\n';
cout << "Decimal " << setbase(10) << 196 << '\n';
cout << "Octal " <<setbase(8) << 196 << '\n';
cout.setf(ios::hex, ios::oct | ios::hex);
Result:
Hexadecimal c4
Decimal 196
Octal 304
Reset to Hex c4
Reset basefield setting 196
18.4.5 setfill
Remarks
Use the manipulator setfill() directly in the output to fill blank spaces with character c.
Returns a smanip type, which is an implementation defined type.
See Also
basic_ios::fill
int main()
{
using namespace std;
cout.width(8);
cout << setfill('*') << "Hi!" << "\n";
char fill = cout.fill();
cout << "The filler is a " << fill << endl;
return 0;
}
Result:
Hi!*****
The filler is a *
18.4.6 setprecision
Remarks
Use the manipulator setprecision() directly in the output stream with floating point
numbers to limit the number of digits. You may use setprecision() with scientific or non-
scientific floating point numbers.
With the flag ios::floatfield set, the number in setprecision refers to the total number of
significant digits generated. If the settings are for either ios::scientific or ios::fixed then
the setprecision refers to the number of digits after the decimal place.
This means that ios::scientific will have one more significant digit than ios::floatfield,
and ios::fixed will have a varying number of digits.
Returns a smanip type, which is an implementation defined type.
See Also
ios_base::setf(), ios_base::precision()
int main()
{
using namespace std;
cout << "Original: " << 321.123456 << endl;
cout << "Precision set: " << setprecision(8)
<< 321.123456 << endl;
return 0;
}
Result:
Original: 321.123
Precision set: 321.12346
18.4.7 setw
Remarks
Use the manipulator setw() directly in a stream to set the field size for output. A pointer to
ostream is returned.
See Also
ios_base::width()
int main()
{
using namespace std;
cout << setw(8)
<< setfill('*')
<< "Hi!" << endl;
return 0;
}
Result:
Hi!*****
Remarks
Use an overloaded manipulator to provide special and unique input handling
characteristics for your class.
Returns a pointer to stream object.
Listing: Example of overloaded manipulator usage:
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 509
Standard manipulators
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cctype>
char buffer[80];
char *Password = "CodeWarrior";
struct verify
{
explicit verify(char* check) : check_(check) {}
char* check_;
};
int main()
{
using namespace std;
cin >> verify(StrUpr(Password));
cout << "Log in was Completed ! \n";
return 0;
}
attempts--;
} while(attempts > 0);
cout << "All Tries failed \n";
exit(1);
return stream;
}
Result:
Enter password: <codewarrior>
Enter password: <mw>
Enter password: <CodeWarrior>
Log in was Completed !
The header <sstream> includes classes and types that associate stream buffers with string
objects for input and output manipulations.
NOTE
The class basic_string is discussed in previous chapters.
The template class basic_stringbuf is derived from basic_streambuf and used to associate
both input and output streams with an object of class basic_string.
The basic_stringbuf has two constructors to create a string buffer for characters for input/
output.
explicit basic_stringbuf(ios_base::openmode which = ios_base::in | ios_base:out);
Remarks
The basic_stringbuf constructor is used to create an object usually as an intermediate
storage object for input and output. The overloaded constructor is used to determine the
input or output attributes of the basic_string object when it is created.
No array object is allocated for the first basic_stringbuf constructor.
Listing: Example of basic_stringbuf::basic_stringbuf() usage:
#include <iostream>
#include <sstream>
int main()
stringbuf strbuf;
strbuf.pubsetbuf('\0', size);
strbuf.sputn("ABCDE",50);
char ch;
ch =strbuf.snextc();
ch = strbuf.snextc();
Result:
BC
19.2.2.1 basic_stringbuf::str
Remarks
The function str() freezes the buffer then returns a basic_string object.
The function str(const string s) assigns the value of the string `s' to the stringbuf object.
The no argument version returns a basic_string if successful. The function with an
argument has no return.
Listing: Example of basic_stringbuf::str() usage:
#include <iostream>
#include <sstream>
#include <cstring>
int main()
{
using namespace std;
string buf;
stringbuf strbuf(buf, ios::in | ios::out);
int size;
size = strlen(CW);
strbuf.sputn(CW, size);
size = strlen(AW);
strbuf.sputn(AW, size);
return 0;
}
Results
CodeWarrior - "Software at Work"
We Listen we Act
19.2.3.1 basic_stringbuf::underflow
Remarks
The function underflow overrides the basic_streambuf virtual function.
Returns the first character of the pending sequence and does not increment the get
pointer. If the position is null returns traits::eof() to indicate failure.
See Also
basic_streambuf::underflow()
19.2.3.2 basic_stringbuf::pbackfail
Remarks
The function pbackfail overrides the basic_streambuf virtual function.
The function pbackfail() is only called when a put back operation really has failed and
returns traits::eof. If success occurs the return is undefined.
See Also
basic_streambuf::pbackfail()
19.2.3.3 basic_stringbuf::overflow
Remarks
The function overflow overrides the basic_streambuf virtual function.
The function returns traits::eof() for failure or some unspecified result to indicate
success.
See Also
basic_streambuf::overflow()
19.2.3.4 basic_stringbuf::seekoff
Remarks
The function seekoff overrides the basic_streambuf virtual function.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 515
Template class basic_istringstream
19.2.3.5 basic_stringbuf::seekpos
Remarks
If the open mode is in or out, the function alters the stream position of both the input and
output sequences. If the open mode is in, it alters the stream position of the input
sequence. If the open mode is out, it alters the stream position of the output sequence. If
sp is an invalid stream position, the operation fails and the return value is
pos_type(off_type(-1)). Otherwise, the function returns the current new position.
If neither the in or out sequence is positioned, pos_type(off_type(-1)) is returned.
See Also
basic_streambuf::seekpos()
Remarks
The basic_istringstream constructor is overloaded to accept an object of class basic_string
for input.
See Also
basic_ostringstream, basic_stringstream
int main()
{
using namespace std;
string sBuffer = "3 12.3 line";
int num = 0;
double flt = 0;
char szArr[20] = "\0";
cout << num << " " << flt << " "
<< szArr << endl;
return 0;
}
Result
3 12.3 line
19.3.2.1 basic_istringstream::rdbuf
Remarks
To manipulate a stream for random access or synchronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
A pointer to an object of type basic_stringbuf sb is returned by the rdbuf function.
See Also
basic_ostringstream::rdbuf()
basic_ios::rdbuf()
basic_stringstream::rdbuf()
Listing: Example of basic_istringstream::rdbuf() usage.
#include <iostream>
#include <sstream>
int main()
{
using namespace std;
istringstream ist(buf);
istream in(ist.rdbuf());
in.seekg(25);
in.get(words,50);
cout << words;
return 0
}
Result
"Software at work"
19.3.2.2 basic_istringstream::str
Remarks
The function str() freezes the buffer then returns a basic_string object.
The function str(const string s) assigns the value of the string `s' to the stringbuf object.
basic_ostringstream.str()
basic_stringstream::str()
int main()
{
using namespace std;
istringstream istr(buf);
cout << istr.str();
return 0;
}
Result:
CodeWarrior - "Software at Work"
explicit basic_ostringstream
(ios_base::openmode which = ios_base::out);
explicit basic_ostringstream
(const basic_string<charT> &str, ios_base::openmode which = ios_base::out);
Remarks
The basic_ostringstream constructor is overloaded to accept an object of class basic_string
for output.
See Also
basic_istringstream, basic_stringstream
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in("ewl-test");
if(!in.is_open())
{cout << "can't open file for input"; exit(1);}
ostringstream Paragraph;
char ch ='\0';
while((ch = in.get()) != EOF)
{
Paragraph << ch;
}
cout << Paragraph.str();
in.close();
return 0;
}
Result:
CodeWarrior - "Software at Work"
Registered Trademark
19.4.2.1 basic_ostringstream::rdbuf
Remarks
To manipulate a stream for random access or synchronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
A pointer to an object of type basic_stringbuf sb is returned by the rdbuf function.
See Also
basic_ostringstream::rdbuf()
basic_ios::rdbuf()
basic_stringstream::rdbuf()
int main()
{
using namespace std;
ostringstream ostr(motto);
streampos cur_pos(0), start_pos(0);
cout << "The original array was :\n"
<< motto << "\n\n";
// associate buffer
stringbuf *strbuf(ostr.rdbuf());
streamoff str_off = 10;
cur_pos = ostr.tellp();
cout << "The current position is "
<< static_cast<streamoff>(cur_pos);
<< " from the beginning\n";
ostr.seekp(str_off);
cur_pos = ostr.tellp();
cout << "The current position is "
<< static_cast<streamoff>(cur_pos);
<< " from the beginning\n";
strbuf->sputc('\0');
cout << "The stringbuf array is\n"
<< strbuf->str() << "\n\n";
Results:
The original array was :
CodeWarrior - "Software at Work"
The current position is 0 from the beginning
The current position is 10 from the beginning
19.4.2.2 basic_ostringstream::str
Remarks
The function str() freezes the buffer then returns a basic_string object.
The function str(const string s) assigns the value of the string `s' to the stringbuf object.
The no argument version returns a basic_string if successful. The function with an
argument has no return.
See Also
basic_stringbuf::str(), basic_istringstream.str()
basic_stringstream::str()
int main()
{
using namespace std;
ostringstream out;
Result:
Ask the teacher anything
OK, what is 2 + 2?
2 plus 2 equals 4?
Remarks
The basic_stringstream constructor is overloaded to accept an object of class basic_string
for input or output.
See Also
basic_ostringstream, basic_istringstream
int main()
{
using namespace std;
stringstream iost;
char word[20];
long num;
double real;
Result
ABCD 22 33.33
19.5.2.1 basic_stringstream::rdbuf
Remarks
To manipulate a stream for random access or synchronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
A pointer to an object of type basic_stringbuf sb is returned by the rdbuf function.
See Also
Template class basic_istringstream
Class basic_ostringstream
Listing: Example of basic_stringstream::rdbuf() usage
#include <iostream>
#include <iostream>
#include <sstream>
int main()
{
using namespace std;
stringstream ist(buf, ios::in);
istream in(ist.rdbuf());
in.seekg(25);
in.get(words,50);
cout << words;
Result
"Software at Work"
19.5.2.2 basic_stringstream::str
Remarks
The function str() freezes the buffer then returns a basic_string object.
The function str(const string s) assigns the value of the string `s' to the stringbuf object.
The no argument version returns a basic_string if successful. The function with an
argument has no return.
See Also
basic_stringbuf::str()
basic_ostringstream.str()
basic_istringstream::str()
int main()
{
using namespace std;
stringstream iost(buf, ios::in);
cout << iost.str();
return 0;
}
Result
CodeWarrior - "Software at Work"
The header <fstream> defines template classes and types to assist in reading and writing of
files.
A class to provide for input and output file stream buffering mechanisms.
The filebuf class is derived from the streambuf class and provides a buffer for file output
and or input.
20.3.1.1 Constructor
To construct and initialize a filebuf object.
basic_filebuf()
Remarks
The constructor opens a basic_filebuf object and initializes it with basic_streambuf<charT,
traits>() and if successful is_open() is false.
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
int main()
{
using namespace std;
FILE *fp = fopen( inFile, "a+");
filebuf in(fp);
in.close();
return 0;
}
Result:
The file ewl-test now contains:
CodeWarrior "Software at Work"
trademark
20.3.1.2 Destructor
To remove the basic_filebuf object from memory.
virtual ~basic_filebuf();
20.3.2.1 basic_filebuf::is_open
Remarks
Use the function is_open() for a filebuf stream to ensure it is open before attempting to do
any input or output operation on the stream.
Returns true if stream is available and open.
See Also
For example of basic_filebuf::is_open() usage see basic_filebuf::basic_filebuf
20.3.2.2 basic_filebuf::open
Remarks
You would use the function open() to open a filebuf object and associate it with a file.
You may use open() to reopen a buffer and associate it if the object was closed but not
destroyed.
If an attempt is made to open a file in an inappropriate file opening mode, the file will not
open and a test for the object will not give false, therefore use the function is_open() to
check for file openings.
If successful the this pointer is returned, if is_open() equals true then a null pointer is
returned.
Table 20-1. Legal basic_filebuf file opening modes
Opening Modes stdio equivalent
Input Only
ios:: in "r"
ios:: binary | ios::in "rb"
Output only
ios::out "w"
ios::binary | ios::out "wb"
ios::out | ios::trunc "w"
ios::binary | ios::out | ios::trunc "wb"
ios::out | ios::app "a"
Input and Output
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
#include <fstream>
#include <cstdlib>
int main(){
using namespace std;
filebuf in;
in.open(inFile, ios::out | ios::app);
if(!in.is_open())
{cout << "could not open file"; exit(1);}
Result:
The file ewl-test now contains:
CodeWarrior "Software at Work"
registered trademark
20.3.2.3 basic_filebuf::close
Remarks
The function close() would remove the stream from memory but will not remove the
filebuf object. You may re-open a filebuf stream that was closed using the close()
function.
The this pointer is returned with success, otherwise a null pointer is returned.
See Also
For example of basic_filebuf::close() usage see basic_filebuf::open().
20.3.3.1 basic_filebuf::showmanyc
Overrides basic_streambuf::showmanyc().
Remarks
Behaves the same as basic_sreambuf::showmanyc().
20.3.3.2 basic_filebuf::underflow
Overrides basic_streambuf::underflow();
Remarks
A sequence of characters is read from the input sequence as though they were read from
the associated file into an internal buffer. This must be done so that the class can recover
the position corresponding to each character between intern_buf and intern_end.
20.3.3.3 basic_filebuf::pbackfail
Overrides basic_streambuf::pbackfail().
Remarks
This function puts back the characters designated by c to the input sequence if possible.
Returns traits::eof() if failure and returns either the character put back or
traits::not_eof(c) for success.
20.3.3.4 basic_filebuf::overflow
Overrides basic_streambuf::overflow()
virtual int_type overflow
(int_type c = traits::eof());
Remarks
Behaves the same as basic_streambuf<charT, traits>::overflow(c) except the behavior of
consuming characters is performed by conversion.
Returns traits::eof() with failure.
20.3.3.5 basic_filebuf::seekoff
Overrides basic_streambuf::seekoff()
virtual pos_type seekoff
(off_type off,
ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
Remarks
Sets the offset position of the stream as if using the C standard library function fseek(file,
off, whence).
Seekoff function returns a newly formed pos_type object which contains all information
needed to determine the current position if successful. Returns an invalid stream position
if it fails.
20.3.3.6 basic_filebuf::seekpos
Overrides basic_streambuf::seekpos()
virtual pos_type seekpos
(pos_type sp,
ios_base::openmode which =
ios_base::in | ios_base::out);
Remarks
Seekpos function returns a newly formed pos_type object which contains all information
needed to determine the current position if successful. Returns an invalid stream position
if it fails.
20.3.3.7 basic_filebuf::setbuf
Overrides basic_streambuf::setbuf()
Remarks
Setbuf returns zero if the file pointer fp is a null pointer. Otherwise, it calls setvbuf(fp,
(char *)buffer, _IOFBF, n * sizeof (E)) to offer the array of n elements beginning at s as a
buffer for the stream. If that function returns a nonzero value, the function returns a null
pointer. Otherwise, the this pointer is returned to signal success.
20.3.3.8 basic_filebuf::sync
Overrides basic_streambuf::sync
Remarks
This protected member function returns zero if the file pointer fp is a null pointer.
Otherwise, it returns fflush(fp) to flush any pending output to the stream.
20.3.3.9 basic_filebuf::imbue
Overrides basic_streambuf::imbue
Remarks
After this function is called, inserted or extracted characters will be converted according
to loc until another call is made to imbue.
Remarks
The constructor creates a stream for file input. It is overloaded to either create and
initialize when called or to simply create a class and be opened using the open() member
function. The default opening mode is ios::in. See basic_filebuf::open() for valid open
mode settings.
See basic_ifstream::open for legal opening modes.
See Also
basic_ifstream::open() for overloaded form usage.
Listing: Example of basic_ifstream::basic_ifstream() constructor usage:
// The ewl-test file contains:
// CodeWarrior "Software at Work"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in(inFile, ios::in);
if(!in.is_open())
{cout << "can't open input file"; exit(1);}
char c ='\0';
while(in.good())
{
if(c) cout << c;
in.get(c);
}
in.close();
return 0;
}
Result:
CodeWarrior "Software at Work"
20.4.2.1 basic_ifstream::rdbuf
Remarks
In order to manipulate for random access or use an ifstream stream for both input and
output you need to manipulate the base buffer. The function rdbuf() returns a pointer to
this buffer for manipulation.
Returns a pointer to type basic_filebuf.
Listing: Example of basic_ifstream::rdbuf() usage:
// The ewl-test file contains originally
// CodeWarrior "Software at Work"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream inOut(inFile, ios::in | ios::out);
if(!inOut.is_open())
{cout << "Could not open file"; exit(1);}
ostream Out(inOut.rdbuf());
char str[] = "\n\tRegistered Trademark";
inOut.rdbuf()->pubseekoff(0, ios::end);
Out << str;
inOut.close();
return 0;
}
Result:
The File now reads:
CodeWarrior "Software at Work"
Registered Trademark
20.4.2.2 basic_ifstream::is_open
Remarks
Use is_open() to test that a stream is indeed open and ready for input from the file.
Returns true if file is open.
See Also
For example of basic_ifstream::is_open() usage see basic_ifstream::basic_ifstream()
20.4.2.3 basic_ifstream::open
Remarks
The default open mode is ios::in, but can be one of several modes. (see below) A stream
is opened and prepared for input or output as selected.
There is no return.
If an attempt is made to open a file in an inappropriate file opening mode, the file will not
open and a test for the object will not give false, therefore use the function is_open() to
check for file openings.
Table 20-2. Legal basic_ifstream file opening modes
Opening Modes stdio equivalent
Input Only
ios:: in "r"
ios:: binary | ios::in "rb"
Input and Output
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ifstream in;
in.open(inFile);
if(!in.is_open())
{cout << "can't open input file"; exit(1);}
char c = NULL;
while((c = in.get()) != EOF)
{
cout << c;
}
in.close();
return 0;
}
Result:
CodeWarrior "Software at Work"
20.4.2.4 basic_ifstream::close
void close();
Remarks
The close() function closes the stream for operation but does not destroy the ifstream
object so it may be re-opened at a later time. If the function fails, it calls setstate(failbit),
which may throw an exception.
There is no return.
See Also
For example of basic_ifstream::close() usage see basic_ifstream::basic_ifstream()
NOTE
The basic_ofstream class supports writing to a file. It uses a
basic_filebuf object to control the sequence. That object is
represented here as basic_filebuf sb.
The basic_ofstream class provides for mechanisms specific to output file streams.
explicit basic_ofstream
Remarks
The class basic_ ofstream creates an object for handling file output. It may be opened later
using the ofstream:: open() member function. It may also be associated with a file when
the object is declared. The default open mode is ios::out.
There are only certain valid file opening modes for an ofstream object. See
basic_ofstream::open for a list of valid opening modes.
Listing: Example of basic_ofstream::ofstream() usage:
// Before the operation the file ewl-test
// may or may not exist.
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ofstream out(outFile);
if(!out.is_open())
{cout << "file not opened"; exit(1);}
out.close();
Result:
This is an annotated reference that contains a description of the Working ANSI C++
Standard Library and other facilities of the Embedded Warrior Library.
20.5.2.1 basic_ofstream::rdbuf
Remarks
In order to manipulate a stream for random access or other operations you must use the
streams base buffer. The member function rdbuf() is used to return a pointer to this buffer.
A pointer to basic_filebuf type is returned.
Listing: Example of basic_ofstream::rdbuf() usage:
// The file ewl-test before the operation contains:
// This is an annotated reference that contains a description
// of the Working ANSI C++ Standard Library and other
// facilities of the Embedded Warrior Library
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
ofstream out(outFile, ios::in | ios::out);
if(!out.is_open())
{cout << "could not open file for output"; exit(1);}
istream inOut(out.rdbuf());
char ch;
while((ch = inOut.get()) != EOF)
{
cout.put(ch);
}
Result:
This is an annotated reference that contains a description of the Working ANSI C++
Standard Library and other facilities of the Embedded Warrior Library.
This is an annotated reference that contains a description of the Working ANSI C++
Standard Library and other facilities of the Embedded Warrior Library.
And so it goes...
20.5.2.2 basic_ofstream::is_open
bool is_open();
Remarks
The is_open() function is used to check that a file stream was indeed opened and ready for
output. You should always test with this function after using the constructor or the open()
function to open a stream.
If an attempt is made to open a file in an inappropriate file opening mode, the file will not
open and a test for the object will not give false, therefore use the function is_open() to
check for file openings.
Returns true if file stream is open and available for output.
See Also
For example of basic_ofstream::is_open() usage see basic_ofstream::ofstream()
20.5.2.3 basic_ofstream::open
Remarks
The function open() opens a file stream for output. The default mode is ios::out, but may
be any valid open mode (see below.) If failure occurs open() calls setstate(failbit) which
may throw an exception.
There is no return.
Table 20-3. Legal basic_ofstream file opening modes.
Opening Modes stdio equivalent
Output only
ios::out "w"
ios::binary | ios::out "wb"
ios::out | ios::trunc "w"
ios::binary | ios::out | ios::trunc "wb"
ios::out | ios::app "a"
Input and Output
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
#include <iostream>
#include <fstream>
#include <cstdlib>
out.close();
return 0;
}
Result:
After the operation ewl-test contained
Chapter One
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
542 Freescale Semiconductor, Inc.
Chapter 20 File Based Streams
This is an annotated reference that contains a description of the Working ANSI C++
Standard Library and other facilities of the Embedded Warrior Library.
20.5.2.4 basic_ofstream::close
The member function closes the stream but does not destroy it.
void close();
Remarks
Use the function close() to close a stream. It may be re-opened at a later time using the
member function open(). If failure occurs open() calls setstate(failbit) which may throw
an exception.
There is no return.
See Also
For example of basic_ofstream::close() usage see basic_ofstream().
template class for the association of a file for input and output.
A
Remarks
The basic_fstream class is derived from basic_iostream and a basic_filebuf object is
initialized at construction.
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
fstream inOut(inFile, ios::in | ios::out);
if(!inOut.is_open())
{cout << "Could not open file"; exit(1);}
inOut.clear();
inOut << str;
inOut.close();
return 0;
}
Result:
CodeWarrior "Software at Work"
The File now reads:
CodeWarrior "Software at Work"
Registered Trademark
20.6.2.1 basic_fstream::rdbuf
Remarks
In order to manipulate for random access or use an fstream stream you may need to
manipulate the base buffer. The function rdbuf() returns a pointer to this buffer for
manipulation.
A pointer to type basic_filebuf is returned.
Listing: Example of basic_fstream::rdbuf() usage
// The ewl-test file contains originally
// CodeWarrior "Software at Work"
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
using namespace std;
fstream inOut;
inOut.open(inFile, ios::in | ios::out);
if(!inOut.is_open())
{cout << "Could not open file"; exit(1);}
Result:
The File now reads:
CodeWarrior "Software at Work"
Registered Trademark
20.6.2.2 basic_fstream::is_open
Test to ensure basic_fstream file is open and available for reading or writing.
Remarks
Use the function is_open() for a basic_fstream file to ensure it is open before attempting to
do any input or output operation on a file.
20.6.2.3 basic_fstream::open
Remarks
You would use the function open() to open a basic_fstream object and associate it with a
file. You may use open() to reopen a file and associate it if the object was closed but not
destroyed.
If an attempt is made to open a file in an inappropriate file opening mode, the file will not
open and a test for the object will not give false, therefore use the function is_open() to
check for file openings.
There is no return value.
Table 20-4. Legal file opening modes
Opening Modes stdio equivalent
Input Only
ios:: in "r"
ios:: binary | ios::in "rb"
Output only
ios::out "w"
ios::binary | ios::out "wb"
ios::out | ios::trunc "w"
ios::binary | ios::out | ios::trunc "wb"
ios::out | ios::app "a"
Input and Output
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
See Also
20.6.2.4 basic_fstream::close
The member function closes the stream but does not destroy it.
void close();
Remarks
Use the function close() to close a stream. It may be re-opened at a later time using the
member function open(). If failure occurs open() calls setstate(failbit) which may throw
an exception.
There is no return value.
See Also
For an example, see Example of basic_fstream:: basic_fstream() usage.
The header <strstream> defines streambuf derived classes that allow for the formatting
and storage of character array based buffers, as well as their input and output.
The chapter is constructed in the following sub sections and is guided by annex D of the
ISO (International Organization for Standardization) C++ Standard.
• Strstreambuf Class a base class for strstream classes
• Istrstream Class a strstream class for input
• Ostrstream Class a strstream class for output
• Strstream Class a class for input and output
The class strstreambuf is derived from streambuf to associate a stream with an in memory
character array.
The strstreambuf class includes virtual protected and public member functions
• freeze freezes the buffer
• pcount determines the buffer size
• str returns a string
• setbuf a virtual function to set the buffer
22.2.1.1 Constructors
Constructs an object of type streambuf.
explicit strstreambuf(streamsize alsize_arg = 0);
strstreambuf(void* (*palloc_arg)(size_t),
void (*pfree_arg)(void*));
Dynamic constructors
strstreambuf(char* gnext_arg, streamsize n, char* pbeg_arg = 0);
Remarks
The constructor sets all pointer member objects to null pointers.
The strstreambuf object is used usually for an intermediate storage object for input and
output. The overloaded constructor that is used determines the attributes of the array
object when it is created. These might be allocated, or dynamic and are stored in a
bitmask type. The first two constructors listed allow for dynamic allocation. The
constructors with character array arguments will use that character array for a buffer.
22.2.1.2 Destructor
virtual ~~strstreambuf();
Remarks
Removes the object from memory.
22.2.2.1 freeze
Remarks
The function freeze() stops allocation if the strstreambuf object is using dynamic
allocation and prevents the destructor from freeing the allocation.
The function freeze(false) releases the freeze to allow for destruction.
There is no return.
Listing: Example of strstreambuf::freeze() usage:
#include <iostream>
#include <strstream>
#include <string.h>
22.2.2.2 pcount
Remarks
The function pcount() is used to determine the offset of the next character position from
the beginning of the buffer.
For an example of strstreambuf::pcount() usage refer to strstreambuf::freeze.
22.2.2.3 str
Remarks
The function str() freezes the buffer and appends a null character then returns the
beginning pointer for the input sequence. The user is responsible for destruction of any
dynamically allocated buffer.
int main()
{
ostrstream ostr(buf, size);
ostr << arr;
// associate buffer
strstreambuf *strbuf(ostr.rdbuf());
// do some manipulations
strbuf->pubseekoff(10,ios::beg);
strbuf->sputc('\0');
strbuf->pubseekoff(0, ios::beg);
cout << "The original array was\n" << arr << "\n\n";
cout << "The strstreambuf array is\n"
<< strbuf->str() << "\n\n";
cout << "The ostrstream array is now\n" << buf;
return 0;
}
22.2.3.1 setbuf
Remarks
The function setbuf() is overridden in strstream classes.
The this pointer is returned.
22.2.3.2 seekoff
Alters the stream position within one of the controlled sequences if possible.
virtual pos_type seekoff(
off_type off,
ios_base::seekdir way,
ios_base::openmode which = ios_base::in | ios_base::out);
Remarks
The function seekoff() is overridden in strstream classes.
Returns new stream position if successful. Otherwise, it returns pos_type(off_type(-1)).
22.2.3.3 seekpos
ios_base::openmode
which = ios_base::in | ios_base::out);
Remarks
The function seekpos() is overridden in strstream classes.
Returns new stream position if successful. Otherwise, it returns pos_type(off_type(-1)).
22.2.3.4 underflow
This function attempts to extract the current item from the input buffer and advance the
current stream position. The item is returned as (int)(unsigned char).
Remarks
The virtual function underflow() is called when a character is not available for input.
There are many constraints for underflow().
The pending sequence of characters is a concatenation of end pointer minus the get
pointer plus some sequence of characters to be read from input.
Returns the result character if the sequence is not empty, which is the first character in
the sequence or the next character in the sequence.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
556 Freescale Semiconductor, Inc.
Chapter 22 Strstream
Returns the backup sequence if the beginning pointer is null or the sequence is empty.
Otherwise the sequence is the get pointer minus the beginning pointer.
If the position is null, returns traits::eof() to indicate failure. Otherwise, it returns the
current element in the input stream.
22.2.3.5 pbackfail
Remarks
The resulting conditions are the same as the function underflow().
The function pbackfail() is only called when a put back operation really has failed and
returns traits::eof. If successful, returns traits::not_eof(c).
22.2.3.6 overflow
Remarks
The pending sequence is defined as the concatenation of the put pointer minus the
beginning pointer plus either the sequence of characters or an empty sequence, unless the
beginning pointer is null in which case the pending sequence is an empty sequence.
This function is called by sputc() and sputn() when the buffer is not large enough to hold
the output sequence.
Overriding this function requires that:
• When overridden by a derived class how characters are consumed must be specified.
• After the overflow either the beginning pointer must be null or the beginning and put
pointer must both be set to the same non-null value.
The function may fail if appending characters to an output stream fails or failure to set the
previous requirement occurs.
The function returns traits::eof() for failure or traits::not_eof(c) to indicate success.
The class istrstream is used to create and associate a stream with an array for input.
22.3.1.1 Constructors
Creates an array based stream for input.
explicit istrstream(const char* s);
explicit istrstream(char* s);
istrstream(const char* s, streamsize n);
istrstream(char* s, streamsize n);
Remarks
The istrstream constructor is overloaded to accept a dynamic or pre-allocated character
based array for input. It is also overloaded to limit the size of the allocation to prevent
accidental overflow.
Listing: Example of usage.
#include <iostream>
#include <strstream>
int main()
{
char arr[4][20];
double d;
long i;
istrstream istr(buf);
istr >> arr[0] >> d >> arr[1] >> arr[2] >> arr[3] >> i;
cout << arr[0] << " is " << d << "\n"
<< arr[1] << " is " << arr[2] << "\n"
<< arr[3] << " is " << i << endl;
return 0;
}
Result:
double is 3.21
string is array
int is 321
22.3.1.2 Destructor
virtual ~istrstream();
Remarks
The istrstream destructor removes the istrstream object from memory.
22.3.2.1 rdbuf
Remarks
To manipulate a stream for random access or sychronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
Returns a pointer to strstreambuf.
For an example of istrstream::rdbuf() usage refer to strstreambuf::str()
22.3.2.2 str
Remarks
The function str() freezes and terminates the character array stored in the buffer with a
null character. It then returns the null terminated character array.
A null terminated char array is returned.
Listing: Example of istrstream::str() usage.
#include <iostream>
#include <strstream>
int main()
{
istrstream istr(buf, size);
cout << istr.str();
return 0;
}
Result:
CodeWarrior - Software at Work
The class ostrstream is used to create and associate a stream with an array for output.
22.4.1.1 Constructors
Creates a stream and associates it with a char array for output.
Remarks
The ostrstream class is overloaded for association with a pre allocated array or for
dynamic allocation.
When using an ostrstream object the user must supply a null character for termination.
When storing a string which is already null terminated that null terminator is stripped off
to allow for appending.
Listing: Example of ostrstream usage.
#include <iostream>
#include <strstream>
int main()
{
ostrstream out;
out << "Ask the teacher anything you want to know" << ends;
istream inOut(out.rdbuf() );
char c;
while( inOut.get(c) ) cout.put(c);
return 0;
}
Result:
Ask the teacher anything you want to know
22.4.1.2 Destructor
virtual ~ostrstream();
Remarks
An ostrstream destructor removes the ostrstream object from memory.
22.4.2.1 freeze
Remarks
This member function calls rdbuf()-> freeze(freezeit).
int main()
{
ostrstream out;
out << "CodeWarrior " << 1234;
out << "the size of the array so far is "
<< out.pcount() << " characters \n";
out << " Software" << '\0';
out.freeze(); // freezes so no more growth can occur
out << " at work" << ends;
out << "the final size of the array is "
<<out.pcount() << " characters \n";
22.4.2.2 pcount
Determines the number of bytes offset from the current stream position to the beginning
of the array.
Remarks
The function pcount() is used to determine the offset of the array. This may not equal to
the number of characters inserted due to possible positioning operations.
Returns an int_type that is the length of the array.
Listing: Example of ostrstream pcount() usage.
int main()
ostrstream out;
return 0;
22.4.2.3 rdbuf
Remarks
To manipulate a stream for random access or sychronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
Returns a pointer to strstreambuf.
For an example of ostrstream rdbuf() usage refer to streambuf::pubseekoff()
22.4.2.4 str
char* str();
Remarks
The class strstream associates a stream with an array buffer for input and or output.
22.5.2.1 Constructors
Creates a stream and associates it with a character array for input and output.
strstream();
strstream(char* s, int n, ios_base::openmode mode =
ios_base::in|ios_base::out);
Remarks
The strstream constructor is overloaded for association with a pre allocated array or for
dynamic allocation.
22.5.2.2 Destructor
virtual ~strstream();
Remarks
Removes the strstream object from memory.
22.5.3.1 freeze
Remarks
The function freeze stops dynamic allocation of a buffer.
22.5.3.2 pcount
Determines the number of bytes offset from the current stream position to the beginning
of the array.
Remarks
The function pcount() is used to determine the offset of the array. This may not equal to
the number of characters inserted due to possible positioning operations.
Returns an int_type that is the length of the array.
22.5.3.3 rdbuf
Remarks
To manipulate a stream for random access or sychronization it is necessary to retrieve a
pointer to the streams buffer. The function rdbuf() allows you to retrieve this pointer.
Returns a pointer to strstreambuf.
22.5.3.4 str
char* str();
Remarks
The function str() freezes any dynamic allocation.
Returns a null terminated character array.
class bitvector
{
public:
// types:
typedef Allocator allocator_type;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef bool value_type;
class reference;
class const_reference;
class pointer;
class const_pointer;
class iterator; // random access
a = Allocator());
} // Metrowerks
23.1.1 allocator_type
The single template parameter of bitvector must be an allocator meeting the standard
allocator requirements. This parameter defaults to std::allocator<bool>. Clients can refer
to this type via the nested name: allocator_type.
23.1.2 size_type
23.1.3 difference_type
typedef typename allocator_type::difference_type
difference_type;
23.1.4 value_type
For compatibility with other standard containers, the nested type value_type is defined as
bool.
23.1.5 reference
class reference;
The nested class reference is a "smart reference" class which emulates a reference to an
internal bool. An actual reference ( bool&) can not be used here since the internal bools are
stored as a single bit. In most cases the behavior will be identical to bool&. One exception
is that the reference has a member function named flip() that will change the value of the
underlying bit.
#include <bitvector>
#include <algorithm>
#include <cassert>
int main()
{
Metrowerks::bitvector<> v(3);
Metrowerks::bitvector<>::reference r = v[0];
assert(v[0] == false);
assert(r == false);
r = true;
assert(v[0] == true);
r.flip();
assert(v[0] == false);
v[1] = true;
swap(r, v[1]);
assert(r == true);
assert(v[0] == true);
assert(v[1] == false);
Metrowerks::bitvector<>::pointer p = &r;
assert(*p == true);
*p = false;
assert(v[0] == false);
assert(r == false);
assert(*p == false);
}
NOTE
swap can be called with this reference type, even with an rvalue
reference. As it applies to std::vector<bool>::reference, this is an
extension to the standard. Another extension to better emulate a
real reference is that you can take the address of a reference that
yields the nested type pointer.
23.1.6 const_reference
class const_reference;
The nested class const_reference is a "smart reference" class which emulates a const
reference to an internal bool. An actual reference ( const bool&) can not be used here since
the internal bools are stored as a single bit. In most cases the behavior will be identical to
const bool&. As it applies to std::vector<bool>::const_reference, this is an extension to the
standard. The standard specifies that std::vector<bool>::const_reference is just a bool. But
the following code demonstrates how this proxy class more closely emulates a const bool&
than does a bool. Another extension to better emulate a real const reference is that you
can take the address of a const_reference which yields the nested type const_pointer.
#include <bitvector>
#include <cassert>
int main()
{
Metrowerks::bitvector<> v(3);
Metrowerks::bitvector<>::const_reference cr = v[0];
assert(cr == false);
v[0] = true;
assert(cr == true);
Metrowerks::bitvector<>::const_pointer cp = &cr;
assert(*cp == true);
}
The nested types iterator and pointer are the same type, as are const_iterator and
const_pointer. Both are random access iterators, except that they return reference and
const_reference respectively when dereferenced (as opposed to bool& and const bool&).
The following standard algorithms are specialized for iterator and const_iterator as
appropriate. They will operate on a word at a time instead of a bit at a time for superior
performance.
Iterator copy(Iterator first, Iterator last, Iterator result);
23.2 Constructors
This section explains Constructors.
Constructs an empty bitvector, with the supplied (or defaulted) allocator. It will not throw
an exception unless constructing or copying the allocator throws an exception. The
default allocator, std::allocator<bool>, will not throw in this context.
Postcondition: size() == 0 and capacity() == 0. If an allocator was supplied then
get_allocator() == a, else get_allocator() == Allocator().
Postcondition: size() == distance(first, last) and capacity() >= size(). All elements are
equal to the corresponding values in the range [first, last). If an allocator was supplied
then get_allocator() == a, else get_allocator() == Allocator().
NOTE
The capacity of x is not necessarily duplicated in *this. In
general, the copy will be done with the least amount of capacity
sufficient to hold size() elements.
23.2.1 Destructor
~bitvector();
23.2.2 Assignment
Assigns x to *this.
Postcondition: *this == x.
If capacity() >= distance(first, last), and if no operations on the InputIterator type can
throw, then no exception can be thrown.
23.3 Capacity
23.3.1 size
23.3.2 empty
Returns size() == 0.
Throws nothing.
23.3.3 capacity
Returns the maximum size() that can be achieved before a memory allocation is required.
Throws nothing.
23.3.4 max_size
Returns a maximum size that the bitvector could grow, assuming sufficient memory. This
is a design-time limit.
Throws nothing.
23.3.5 reserve
23.3.6 get_allocator
Returns a copy of the allocator that the bitvector was constructed with. If the copy
constructor of the allocator_type can not throw an exception then get_allocator() is also a
non-throwing operation.
23.4 Iteration
Returns an iterator referring to the first element in the bitvector. If the bitvector is empty,
then returns an iterator equal to end().
Throws nothing.
iterator end();
const_iterator end() const;
Returns an iterator referring to one past the last element in the bitvector. If the bitvector is
empty, then returns an iterator equal to begin().
Throws nothing.
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
Returns std::reverse_iterator's which operate over the range of the bitvector but in reverse
order.
Throws nothing.
23.5 Access
23.5.1 front
Throws nothing.
const_reference at(size_type n) const;
reference at(size_type n);
23.6 Insertion
23.6.1 push_back
23.6.2 insert
Inserts x into the bitvector at position. All elements in the range [position, end()) are
moved down to make room for x. The returned iterator refers to the newly inserted
element having value x.
Precondition: position is an iterator into this bitvector.
Postcondition: If an exception is not thrown, size() is increased by one and
*returned_iterator == x.
Inserts n copies of x into the bitvector at position. All elements in the range [position,
end()) are moved down to make room for the newly inserted elements.
Inserts the range [first, last) into the bitvector at position. All elements in the range
[position, end()) are moved down to make room for the newly inserted elements.
Precondition: position is an iterator into this bitvector. first and last are not iterators into
this bitvector.
Postcondition: If an exception is not thrown, size() is increased by distance(first, last).
23.7 Erasure
23.7.1 pop_back
void pop_back();
23.7.2 clear
void clear();
Throws nothing.
23.7.3 erase
Removes the element at position. Elements in the range (position, end) are moved down
by one in the bitvector. An iterator pointing to the element just after the erased element,
in the modified bitvector, is returned.
Precondition: position is a dereferenceble iterator into this bitvector.
Postcondition: size() is decreased by one.
Throws nothing.
Removes the range of elements [first, last). Elements in the range (last, end) are moved
down by distance(first, last) in the bitvector. An iterator pointing to the element just
after the erased range, in the modified bitvector, is returned.
Precondition: first is a dereferenceble iterator into this bitvector. last is an iterator into
this bitvector. first <= last.
Postcondition: size() is decreased by last-first.
Throws nothing.
23.8 Miscellaneous
This section defines miscellaneous functions.
23.8.1 resize
Changes the size() of the bitvector to sz. If sz is greater than the current size(), extra
elements are appended with the value c.
Postcondition: size() == sz.
23.8.2 swap
Swaps the contents of *this and x. If the allocator_type contains state, the allocators are
also swapped using an unqualified call to swap, with std::swap in scope.
Postcondition: *this == previous value of x and x == previous value of *this.
If swap on the allocator_type can not throw, then this operation will not throw an
exception.
23.8.3 flip
void flip();
23.8.4 invariants
This function checks the objects internal invariants and returns true if all are satisfied. If
it returns false, it indicates a bug either in the bitvector implementation, or in client code.
A common way to use this member is:
assert(v.invariants());
Throws nothing.
Throws nothing.
template <class Allocator>
bool
operator!=(const bitvector<Allocator>& x, const
bitvector<Allocator>& y);
Throws nothing.
template <class Allocator>
bool
operator< (const bitvector<Allocator>& x, const
bitvector<Allocator>& y);
Throws nothing.
template <class Allocator>
bool
operator> (const bitvector<Allocator>& x, const
bitvector<Allocator>& y);
Returns y < x;
Throws nothing.
template <class Allocator>
bool
operator>=(const bitvector<Allocator>& x, const
bitvector<Allocator>& y);
Throws nothing.
template <class Allocator>
bool
operator<=(const bitvector<Allocator>& x, const
bitvector<Allocator>& y);
Throws nothing.
template <class Allocator>
void
swap(bitvector<Allocator>& x, bitvector<Allocator>& y);
Calls x.swap(y);
This chapter is a reference guide to the General utility support in the Embedded Warrior
Library.
This chapter consists of utilities for support of non standard headers.
• Header ewl_utlity
• Basic Compile-Time Transformations
• Type Query
• CV Query
• Type Classification
• POD classification
• Miscellaneous
http://www.boost.org/
NOTE
Unnamed namespaces are displayed using a compiler generated
unique name that has the form: __unnamed_<filename> where
<filename> is the source file name of the main translation unit
that contains the unnamed namespace.
NOTE
When generating multiple template instantiations, the compiler
may choose to optimize functions that have same binary
representation regardless of the specialization being compiled.
This results in smaller code, but while debugging no
breakpoints can be placed inside optimized functions. To
alleviate this, use the ""-Xcfe -fl=dont_inline" switch. For more
information about dont_inline swith, see the <product> C/C++
Compiler User Guide.
24.2.1 remove_const
Will remove the top level const (if present) from a type.
typedef typename
remove_const<T>::type non_const_type;
Remarks
The resulting "non_const_type" will be the same as the input type T, except that if T is
const qualified, that constant qualification will be removed.
24.2.2 remove_volatile
Will remove the top level volatile (if present) from a type.
typedef typename
remove_volatile<T>::type non_volatile_type;
Remarks
The resulting "non_volatile_type" will be the same as the input type T, except that if T is
volatile qualified, that volatile qualification will be removed.
Listing: Example of remove_volatile
typedef typename remove_volatile <volatile int>::type Int;
Int has type int.
24.2.3 remove_cv
Will remove the top level qualifiers (const and/or volatile, if present) from a type.
typedef typename
remove_cv<T>::type non_qualified_type;
Remarks
The resulting "non_qualified_type" will be the same as the input type T, except that if T is
cv qualified, the qualifiers will be removed.
24.2.4 remove_pointer
If given a pointer, returns the type being pointed to. If given a non-pointer type, simply
returns the input.
typedef typename
remove_pointer<T>::type pointed_to_type;
24.2.5 remove_reference
If given a reference, returns the type being referenced. If given a non-reference, simply
returns the input.
typedef typename
remove_reference<T>::type referenced_type;
Int has the type int, and ConstInt has the type const int.
24.2.6 remove_bounds
If given an array type, will return the type of an element in the array. If given a non-array
type, simply returns the input.
24.2.7 remove_all
This transformation will recursively remove cv qualifiers, pointers, references and array
bounds until the type is a fundamental type, enum, union, class or member pointer.
24.3.1 is_same
This struct can be used to tell if two types are the same type or not.
24.4 CV Query
24.4.1 is_const
Returns true if type has a top level const qualifier, else false.
bool b = is_const<T>::value;
24.4.2 is_volatile
Returns true if type has a top level volatile qualifier, else false.
bool b = is_volatile<T>::value;
bool b = is_XXX<T>::value;
• is_array
• is_enum
• is_union
• is_class
There are also five categories that are made up of combinations of the ten basic
categories:
• is_arithmetic - is_integral or is_floating
• is_fundamental - is_arithmetic or is_void
• is_scalar - is_arithmetic or is_pointer or is_member_pointer or is_enum
• is_compound - not is_fundamental
• is_object - anything but a void or reference type
The classifications: is_enum and is_union do not currently work automatically.
Enumerations and unions will be mistakenly classified as class type. This can be
corrected on a case by case basis by specializing is_enum_imp or is_union_imp. These
specializations are in the Metrowerks::details namespace.
is_extension is also provided for those types that we provide as an extension to the C++
standard. is_extension<T>::value will be false for all types except for long long and
unsigned long long.
has_extension is a modified form of is_extension that answers to true if a type is either an
extension or contains an extension.
Listing: Example of is_integral
bool b = is_integral<volatile int>::value;
The value of b is true.
template <>
struct Metrowerks::details::is_enum_imp<MyEnum>
These structs only work on arithmetic types. The type must be constructable by an int and
be less-than comparable.
Remarks
In the Example of is_signed and is_unsigned the signedness of char is tested. Since it is
implementation-defined whether or not char is signed, this is a way to find out how it is
defined. Either b1 will be true and b2 false, or vice-versa.
Listing: Example of is_signed and is_unsigned
bool b1 = is_signed<char>::value;
bool b2 = is_unsigned<char>::value;
• has_trivial_default_ctor
• has_trivial_copy_ctor
• has_trivial_assignment
• has_trivial_dtor
This library will answer correctly for non-class types. But user defined class types will
always answer false to any of these queries. If you create a class with trivial special
members, and you want that class to be able to take advantage of any optimizations that
might arise from the assumption of trivial special members, you can specialize these
structs:
Note that in the Example of specialized structs these specializations need not worry about
cv qualifications. The higher level has_trival_XXX structs do that for you.
Finally there is an is_POD struct that will answer true if a type answers true on all four of
the above queries.
Listing: Example of specialized structs
template <>
struct Metrowerks::details::class_has_trivial_default_ctor<MyClass>
template <>
struct Metrowerks::details::class_has_trivial_copy_ctor<MyClass>
struct Metrowerks::details::class_has_trivial_assignment<MyClass>
template <>
struct Metrowerks::details::class_has_trivial_dtor<MyClass>
24.7 Miscellaneous
Miscellaneous utility functions are included in the EWL Utilities library.
24.7.1 compile_assert
This is a compile time assert. This is a very basic version of this idea. Can be used to test
assertions at compile time.
Listing: Example of compile_assert use
#include <ewl_utility>
foo(const T& t)
{
Metrowerks::compile_assert<sizeof(T) >= sizeof(int)>
T_Must_Be_At_Least_As_Big_As_int;
//...
return t;
}
int main()
{
int i;
foo(i); // ok
char c;
foo(c); // Error : illegal use of incomplete struct/union/class
// 'Metrowerks::compile_assert<0>'
24.7.2 array_size
Given an array type, you can get the size of the array with array_size.
The code fragment array_size<type>::value will only compile if type is an array. It won't
compile if type is a union, struct or class.
Listing: Example usage of array_size
typedef int Array[10];
size_t n = array_size<Array>::value;
24.7.3 can_derive_from
The code fragment can_derive_from<T>::value will be true if T is a class (but not a union),
otherwise it will be false. Only classes which are not unions can be derived from.
bool b = can_derive_from<T>::value;
24.7.4 call_traits
This struct is a collection of type definitions that ease coding of template classes when
the template parameter may be a non-array object, an array, or a reference. The type
definitions specify how to pass a type into a function, and how to pass it back out either
by value, reference or const reference. The interface is:
call_traits<T>::value_type
call_traits<T>::reference
call_traits<T>::const_reference
call_traits<T>::param_type
Remarks
The first three types are suggestions on how to return a type from a function by value,
reference or const reference. The fourth type is a suggestion on how to pass a type into a
method.
The call_traits struct is most useful in avoiding references to a reference which are
currently illegal in C++. Another use is in helping to decay array-type parameters into
pointers. In general, use of call_traits is limited to advanced techniques, and will not
require specializations of call_traits to be made. For example uses of call_traits see
compressed_pair. For an example specialization see alloc_ptr.
24.7.5 is_empty
Answers true if the type is a class or union that has no data members, otherwise answers
false. This is a key struct for determining if the space for an "empty" object can be
optimized away or not.
bool b = is_empty<T>::value;
24.7.6 compressed_pair
Like std::pair, but attempts to optimize away the space for either the first or second
template parameter if the type is "empty". And instead of the members being accessible
via the public data members first and second, they are accessible via member methods
first() and second(). The compressed_pair handles reference types as well as other types
thanks to the call_traits template. This is a good example to study if you're wanting to see
how to take advantage of either call_traits or is_empty. To see an example of how
compressed_pair is used see alloc_ptr.
Remarks
Use of the single argument constructors will fail at compile time (ambiguous call) if
first_type and second_type are the same type.
The swap specialization will call swap on each member if and only if its size has not been
optimized away. The call to swap on each member will look both in std, and in the
member's namespace for the appropriate swap specialization. Thus clients of
compressed_pair need not put swap specializations into namespace std.
A good use of compressed_pair is in the implementation of a container that must store a
function object. Function objects are typically zero-sized classes, but are also allowed to
be ordinary function pointers. If the function object is a zero-sized class, then the
container can optimize its space away by using it as a base class. But if the function
object instantiates to a function pointer, it can not be used as a base class. By putting the
function object into a compressed_pair, the container implementor need not worry
whether it will instantiate to a class or function pointer.
private:
Metrowerks::compressed_pair<T*, Compare> data_;
};
int main()
{
typedef MyContainer<int, std::less<int>> MyContainer1;
typedef MyContainer<int, bool (*)(int, int)> MyContainer2
std::cout << sizeof(MyContainer1) << '\n';
std::cout << sizeof(MyContainer2) << '\n';
}
24.7.7 alloc_ptr
An extension of std::auto_ptr. alloc_ptr will do everything that auto_ptr will do with the
same syntax. Additionally alloc_ptr will deal with array new/delete:
Remarks
By adding the array_deleter<T> template parameter you can enable alloc_ptr to correctly
handle pointers to arrays of elements.
alloc_ptr will also work with allocators which adhere to the standard interface. This
comes in very handy if you are writing a container that is templated on an allocator type.
You can instantiate an alloc_ptr to work with an allocator with:
alloc_ptr<T, Allocator<T>, typename Allocator<T>::size_type> a;
The third parameter can be omitted if the allocator is always going to allocate and
deallocate items one at a time (e.g. node based containers).
alloc_ptr takes full advantage of compressed_pair so that it is as efficient as std::auto_ptr.
The sizeof(alloc_ptr<int>) is only one word. Additionally alloc_ptr will work with a
reference to an allocator instead of an allocator (thanks to call_traits). This is extremely
useful in the implementation of node based containers.
This is essentially the std::auto_ptr interface with a few twists to accommodate allocators
and size parameters.
To enable EWL C++ Debug mode simply uncomment this line in the EWL Configuration
header <ewlconfig> See C++ Switches, Flags and Defines for more information.
#define _EWL_DEBUG
Alternatively you can #define _EWL_DEBUG in a prefix file. Either way, you must rebuild
your C++ library after flipping this switch. Convenience makefiles are provided under
ewl/EWL_C++/ to make this task easier. After rebuilding the C++ library, rebuild your
application and run it. If there are any errors, a std::logic_error will be thrown. If
exceptions are disabled, then instead the error function __ewl_error(const char*) is called.
This function can be defined by client code. There are some sample implementations in
<ewlconfig>. The default simply calls fprintf and abort.
Each container has methods that will invalidate some or all outstanding iterators. If those
iterators are invalidated, then their use (except for assigning a new valid iterator) will
generate an error. An iterator is considered invalidated if it no longer points into the
container, or if the container's method silently causes the iterator to point to a new
element within the container. Some methods (such as swap, or list::splice) will transfer
ownership of outstanding iterators from one container to another, but otherwise leave
them valid.
In this Example of dereference at end: the iterator i is incremented to the end of the
vector and then dereferenced and assigned through. In release mode this is undefined
behavior and may overwrite other important information in your application. However in
debug mode this example prints out:
EWL DEBUG: dereferenced invalid iterator
int main()
{
try
{
std::vector<int> v(10);
std::vector<int>::iterator i = v.begin() + 9;
*i = 9; // ok
++i; // ok
*i = 10; // error
} catch (std::exception& e)
catch (...)
{
std::cerr << "Unknown exception caught\n";
}
}
In the Example of iterator/list mismatch: an iterator is initialized to point into the first list.
But then this iterator is mistakenly used to erase an element from a second list. This is
normally undefined behavior. In debug mode this example prints out:
EWL DEBUG: invalid iterator given to list
int main()
{
try
{
std::list<int> l1(10), l2(10);
std::list<int>::iterator i = l1.begin();
l2.erase(i); // error
}
catch (std::exception& e)
{
std::cerr << e.what() << '\n';
}
catch (...)
{
std::cerr << "Unknown exception caught\n";
}
}
In the Example of use of invalidated iterator: the push_back method on deque invalidates
all iterators. When the loop goes to increment i, it is operating on an invalidated iterator.
This is normally undefined behavior. In debug mode this example prints out:
EWL DEBUG: increment end or invalid iterator
int main()
{
try
{
std::deque<int> d(10);
std::deque<int>::iterator i = d.begin(), e = d.end();
for (; i != e; ++i)
d.push_back(0);
}
catch (std::exception& e)
{
std::cerr << e.what() << '\n';
}
catch (...)
{
std::cerr << "Unknown exception caught\n";
}
}
25.2.1.1 deque
swap
Iterators remain valid, but they now point into the swapped container.
Remarks
The index operator is range checked just like the at() method.
25.2.1.2 list
25.2.1.3 string
25.2.1.4 vector
Various funstions are included for debugging the tree-based container classes map,
multimap, set and multiset classes.
assign
Invalidates all iterators.
insert
No iterators are invalidated.
erase
Only the iterators to the erased elements are invalidated.
clear
Invalidates all iterators.
swap
Iterators remain valid, but they now point into the swapped container.
25.2.1.6 cdeque
Iterators remain valid, but they now point into the swapped container.
Remarks
The index operator is range checked just like the at() method.
25.2.1.7 slist
assign
Invalidates all iterators.
insert
If load_factor() attempts to grow larger than load_factor_limit(), then the table is
rehashed which invalidates all iterators, else no iterators are invalidated.
erase
Only the iterators to the erased elements are invalidated.
clear
Invalidates all iterators.
swap
Iterators remain valid, but they now point into the swapped container.
25.2.2 Invariants
In addition to the iterator checking described above, each container (except string) has a
new member method:
bool invariants() const;
This method can be called at any time to assess the container's class invariants. If the
method returns false, then the container has somehow become corrupted and there is a
bug (most likely in client code, but anything is possible). If the method returns true, then
no errors have been detected. This can easily be used in debug code like:
Listing: Example of invariant deubbging
#include <vector>
#include <cassert>
int main()
{
int iarray[4];
std::vector<int> v(10);
assert(v.invariants());
assert(v.invariants());
The for loop indexing over iarray goes one element too far and steps on the vector. The
assert after the loop detects that the vector has been compromised and fires.
Be warned that the invariants method for some containers can have a significant
computational expense, so this method is not advised for release code (nor are any of the
debug facilities).
This chapter is a reference guide to the hash support in the Embedded Warrior Libraries.
This chapter on EWL implementation of hashes is made up of the following topics. A
separate chapter EWL_Utility is also useful when understanding the methodology.
• General Hash Issues
• Hash_set
• Hash_map
• Hash_fun
Rather than repeat each of these issues for each of the four hash containers, they are
discussed here.
26.1.1 Introduction
These classes are analogous to std::set, std::multiset, std::map and std::multimap, but are
based on a hash table. The design and implementation of these classes has the following
goals:
• High CPU performance
• Minimum memory usage
• Ease of use
• Control over hashing details
int main()
{
Metrowerks::hash_set<int> a;
}
int main()
The short name " ewl" is much more likely to conflict with other's libraries, but as the
implementor of your code you can choose your aliases such that there is no conflict.
using Metrowerks::hash_multiset;
int main()
{
hash_multiset<int> a;
}
Remarks
Anywhere below the declaration, hash_set can be referred to without the use of the
Metrowerks qualifier.
Using directives will import every name in one namespace into another. These can be
used to essentially "turn off" namespaces so that you don't have to deal with them. They
can be used at namespace scope, or to limit their effect, can also be used at function
scope. For example:
Listing: Function Scope
#include <hash_map>
int main()
{
using namespace Metrowerks;
hash_multimap<int, int> a;
}
Remarks
In the above example, any name in the Metrowerks namespace can be used in main
without qualification.
int main()
{
hash_set<int> a;
hash_map<int, int> b;
}
26.1.2.6 Constructors
Each hash container has a constructor which takes the following arguments, with the
following defaults:
size_type num_buckets = 0
float load_factor_limit = 2
float growth_factor = 4
Remarks
Since all arguments have defaults, the constructor serves as a default constructor. It is
also declared explicit to inhibit implicit conversions from the first argument: size_type.
The first argument is a way to specify the initial number of buckets. This was chosen as
the first parameter in order to remain compatible both with previous versions of EWL
hash containers, as well as the SGI hash containers.
The second and third parameters allow client code to initialize the hash and compare
function objects if necessary. This will typically only be necessary if ordinary function
pointers are being used. When function objects are used, the default constructed function
object is often sufficient.
The fourth and fifth parameters allow you to set the initial values of load_factor_limit and
growth_factor. Details on how these parameters interact with the size() and bucket_count()
of the container can be found in the capacity section.
A second constructor also exists that accepts templated input iterators for constructing a
hash container from a range. After the pair of iterators, the six parameters from the first
constructor follow in the same order, and with the same defaults.
26.1.2.8 Capacity
empty, size
and max_size have semantics identical with that described for standard
containers.
Remarks
The load factor of a hash container is the number of elements divided by the number of
buckets:
size()
load_factor = --------------
bucket_count()
During the life time of a container, the load factor is at all times less than or equal to the
load factor limit:
size()
bucket_count()
This is a class invariant. When both size() and bucket_count() are zero, the load_factor is
interpreted to be zero. size() can not be greater than zero if bucket_count() is zero. Client
code can directly or indirectly alter size(), bucket_count() and load_factor_limit(). But at
all times, bucket_count() may be adjusted so that the class invariant is not compromised.
• If client code increases size() via methods such as insert such that the invariant is
about to be violated, bucket_count() will be increased by growth_factor().
• If client code decreases size() via methods such as erase, the invariant can not be
violated.
• If client code increases load_factor_limit(), the invariant can not be violated.
• If client code decreases load_factor_limit() to the point that the invariant would be
violated, then bucket_count() will be increased just enough to satisfy the invariant.
• If client code increases bucket_count(), the invariant can not be violated.
• If client code decreases bucket_count() to the point that the invariant would be
violated, then bucket_count() will be decreased only to the minimum amount such
that the invariant will not be violated.
The final item in the bulleted list results to a "shrink to fit" statement.
myhash.bucket_count(0); // shrink to fit
The above statement will reduce the bucket count to the point that the load_factor() is just
at or below the load_factor_limit().
bucket_count()
load_factor()
load_factor_limit()
The load_factor_limit(float lf) sets the load factor limit. If the new load factor limit is
less than the current load factor limit, the number of buckets may be increased.
You can completely block the automatic change of bucket_count with:
myhash.load_factor_limit(INFINITY);
This may be important if you are wanting outstanding iterators to not be invalidated while
inserting items into the container. The argument to load_factor_limit must be positive,
else an exception of type std::out_of_range is thrown.
The growth_factor functions will read and set the growth_factor. When setting, the new
growth factor must be greater than 1 else an exception of type std::out_of_range is
thrown.
The collision(const_iterator) method will count the number of items in the same bucket
with the referred to item. This may be helpful in diagnosing a poor hash distribution.
26.1.2.9 insert
Remarks
If x does not already exist in the container, it will be inserted. The returned iterator will
point to the newly inserted x, and the bool will be true. If x already exists in the
container, the container is unchanged. The returned iterator will point to the element that
is equal to x, and the bool will be false.
iterator insert(iterator, const value_type& x);
Operates just like the version taking only a value_type. The iterator argument is ignored.
It is only present for compatibility with standard containers.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 615
General Hash Issues
Inserts those elements in (first, last) that don't already exist in the container.
26.1.2.10 insert
The insert for multi-hashed containers functions hash_multiset and hash_multimap have the
following insert methods.
iterator insert(const value_type& x);
Remarks
In the first insert prototype x is inserted into the container and an iterator pointing to the
newly inserted value is returned. If values equal to x already exist in the container, then
the new element is inserted after all other equal elements. This ordering is stable
throughout the lifetime of the container.
In the second prototype insert first checks to see if *p is equivalent to x according to the
compare function. If it is, then x is inserted before p. If not then x is inserted as if the
insert without an iterator was used. An iterator is returned which points to the newly
inserted element.
The final insert prototype inserts (first, last) into the container. Equal elements will be
ordered according to which was inserted first.
26.1.2.11 erase
Remarks
The first erase function erases the item pointed to by position from the container. The
second erases all items in the container that compare equal to x and returns the number of
elements erased. The third erase erases the range (first, last) from the container.
swap(hash_set& y);
26.1.2.12 Observers
Miscellaneous functions used in the hash implementation.
get_allocator() const;
key_comp() const
Returns the comparison function the hash container was constructed with.
value_comp() const
Returns the comparison function used in the underlying hash table. For hash_set and
hash_multiset, this is the same as key_comp().
key_hash()
Returns the hash function the hash container was constructed with.
value_hash()
Returns the hash function used in the underlying hash table. For hash_set and
hash_multiset, this is the same as key_hash().
find
Returns an iterator to the first element in the container that is equal to x, or if x is not in
the container, returns end().
count
Returns a pair of iterators indicating a range in the container such that all elements in the
range are equal to x. If no elements equal to x are in the container, an empty range is
returned.
swap(x, y)
operator == (x, y)
Returns true if x and y contain the same elements in the same order. To accomplish this
they most likely must have the same number of buckets as well.
operator!=
operator != (x, y)
Returns !(x == y)
26.2 Hash_set
26.2.1 Introduction
These containers are in the namespace Metrowerks. See Namespace Issues for details and
hints about how to best take advantage of this fact.
hash_set and hash_multiset are largely compatible with previous versions of these classes
which appeared in namespace std. But see Incompatibility for a short list of
incompatibilities.
int main()
{
std::hash_set<int> a;
}
class hash_(multi)set;
The first parameter is the type of element the set is to contain. It can be almost any type,
but must be copyable.
The second parameter is the hash function used to look up elements. It defaults to the
hash function in <hash_fun>. Client code can use hash<T> as is, specialize it, or supply
completely different hash function objects or hash function pointers. The hash function
must accept a T, and return a size_t.
The third parameter is the comparison function which defaults to std::equal_to<T>. This
function should have equality semantics. A specific requirement is that if two keys
compare equal according to Compare, then they must also produce the same result when
processed by Hash.
The fourth and final parameter is the allocator, which defaults to std::allocator<T>. The
same comments and requirements that appear in the standard for allocators apply here as
well.
26.2.6 hash_set
hash_set is a container based on a hash table that supports fast find, insert and erase. The
elements in a hash_set are unordered. A hash_set does not allow multiple entries of
equivalent elements.
26.3 Hash_map
The hash_map is a container that holds an unordered set of key-value pairs, and no two
keys in the container can compare equal.
hash_multimap permits duplicate entries. Also see the General Hash Issues Introduction.
This header contains two classes:
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 621
Hash_map
• hash_map
• hash_multimap
NOTE
This header is non-standard. The classes herein are offered
as extensions to the C++ standard. They are marked as such
by the namespace Metrowerks.
26.3.1 Introduction
These containers are in the namespace Metrowerks. See Namespace Issues for details and
hints about how to best take advantage of this fact.
hash_map and hash_multimap are largely compatible with previous versions of these
classes which appeared in namespace std. But see Incompatibility for a short list of
incompatibilities.
int main()
{
std::hash_map<int, int> a;
}
class hash_(multi)map;
The first parameter is the type of key the map is to contain. It can be almost any type, but
must be copyable.
The second parameter is the type of value that will be associated with each key. It can be
almost any type, but must be copyable.
The third parameter is the hash function used to look up elements. It defaults to the hash
function in <hash_fun>. Client code can use hash<Key> as is, specialize it, or supply
completely different hash function objects or hash function pointers. The hash function
must accept a Key, and return a size_t.
The fourth parameter is the comparison function which defaults to std::equal_to<Key>.
This function should have equality semantics. A specific requirement is that if two keys
compare equal according to Compare, then they must also produce the same result when
processed by Hash.
The fifth and final parameter is the allocator, which defaults to
std::allocator<std::pair<const Key, T> >. The same comments and requirements that
appear in the standard for allocators apply here as well.
These simply return the result of key_hasher, but with the first operator extracting the
key_type from the value_type before passing the key_type on to key_hasher.
• Key_compare and value_compare are not the same type. key_compare is the
template parameter Compare. value_compare is a nested type which converts
key_compare into a function which accepts a value_type.
• value_compare has the public typedef's
If the key x already exists in the container, returns a reference to the mapped_type
associated with that key. If the key x does not already exist in the container, inserts a new
entry: (x, mapped_type()), and returns a reference to the newly created, default
constructed mapped_type.
26.4 Hash_fun
<hash_fun> declares a templated struct which serves as a function object named hash.
This is the default hash function for all hash containers. As supplied, hash works for
integral types, basic_string types, and char* types (c-strings).
NOTE
This header is non-standard. The classes herein are offered as
extensions to the C++ standard. They are marked as such by the
namespace Metrowerks.
Client code can specialize hash to work for other types.
Alternatively, client code can simply supply customized hash functions to the hash
containers via the template parameters.
The returned size_t should be as evenly distributed as possible in the range [0,
numeric_limits<size_t>::max()]. Logic in the hash containers will take care of folding
this output into the range of the current number of buckets.
If you're already familiar with boost::threads, then you'll be very comfortable with
Metrowerks::threads. The interface closely follows the boost library. There are some
minor differences.
The biggest difference is that the library is part of EWL C++, and lives in namespace
Metrowerks. The entire package can be accessed via <ewl_thread>. It is essentially a fairly
thin C++ wrapper over a sub-set of Posix-threads. And there is also a "single thread"
version where most of the code just does nothing. It is there to ease porting multithreaded
code to a single threaded environment. But be aware that your multithreaded logic may or
may not translate into a working single threaded application (especially if you deal with
condition variables).
The threads library currently has these configuration flags:
Table 27-1. Threads Configuration Flags
Flag Effects
_EWL_SINGLE_THREAD A do-nothing stand-in
_EWL_USE_PTHREADS Poxsix-Threads
_EWL_USE_WINTHREADS Windows threads
EWL C++ will automatically configure itself based on how _EWL_THREADSAFE is set.
However you can override the automatic configuration simply by setting it yourself in
your prefix file or preprocesssor preference panel. You must recompile the C++ library to
have the same setting.
You can now create a runtime check to make sure your EWL C++ is compiled with
consistent settings:
#include <ewl_utility>
int main()
{
check(Metrowerks::ewl_settings());
}
This program will assert if it finds anything inconsistent between itself and the way EWL
C++ was compiled.
class try_mutex
{
public:
typedef /* details */ scoped_lock;
typedef /* details */ scoped_try_lock;
try_mutex();
~try_mutex();
};
class timed_mutex
{
public:
typedef /* details */ scoped_lock;
typedef /* details */ scoped_try_lock;
typedef /* details */ scoped_timed_lock;
timed_mutex();
~timed_mutex();
};
class recursive_mutex
{
public:
class recursive_try_mutex
{
public:
typedef /* details */ scoped_lock;
typedef /* details */ scoped_try_lock;
recursive_try_mutex();
~recursive_try_mutex();
};
class recursive_timed_mutex
{
public:
typedef /* details */ scoped_lock;
typedef /* details */ scoped_try_lock;
typedef /* details */ scoped_timed_lock;
recursive_timed_mutex();
~recursive_timed_mutex();
};
Note that each mutex type has only a default constructor and destructor. It is not
copyable, and it does not have lock and unlock functions. You access this functionality
via one of the nested types:
• scoped_lock
• scoped_try_lock
• scoped_timed_lock
Listing: A scoped_lock
template <typename Mutex>
class scoped_lock
{
public:
typedef Mutex mutex_type;
explicit scoped_lock(mutex_type& m);
scoped_lock(mutex_type& m, bool lock_it);
~scoped_lock();
void lock();
void unlock();
bool locked() const;
operator int bool_type::* () const;
};
You can use the scoped_lock to lock and unlock the associated mutex, and test whether it is
locked or not (the operator bool_type is just a safe way to test the lock in an if statement
like you might a pointer), for example:
if (my_lock) ...
Normally you won't use any of the scoped_lock's members except it's constructor and
destructor. These lock and unlock the mutex respectively.
Listing: Example of lock and unlock usage
#include <ewl_thread>
Metrowerks::mutex foo_mut;
void foo()
{
Metrowerks::mutex::scoped_lock lock(foo_mut);
// only one thread can enter here at a time
} // foo_mut is implicitly unlocked here, no matter how foo returns
In single thread mode, the above example compiles, and the lock simply doesn't do
anything. If you expect foo() to call itself, or to call another function which will lock the
same mutex (before foo releases foo_mut), then you should use a recursive mutex.
A mutex can conveniently be a class member, which can then be used to lock various
member functions on entry. But recall that your class copy constructor will need to create
a fresh mutex when copying, as the mutex itself can not be copied (or assigned to).
In some cases you want to lock the mutex only if you don't have to wait for it. If it is
unlocked, you lock it, else your thread can do something else. Use scoped_try_lock for this
application. Note that not all mutex types support scoped_try_lock (have it as a nested
type). The scoped_try_lock looks just like scoped_lock but adds this member function bool
try_lock(),
void foo()
{
Metrowerks::try_mutex::scoped_try_lock lock(foo_mut, false);
if (lock.try_lock())
{
// got the lock
}
else
{
// do something else
}
}
In the above example, the second parameter in the constructor tells the lock to not lock
the mutex upon construction (else you might have to wait).
Sometimes you are willing to wait for a mutex lock, but only for so long, and then you
want to give up. scoped_timed_lock is the proper lock for this situation. It looks just like a
scoped_lock but adds two members:
These let you specify the amount of time you're willing to wait, either in terms of an
absolute time ( universal_time), or in terms of an interval from the current time
( elapsed_time).
Listing: Example of timed_lock()
This specifies that the thread should quit trying for the lock after 1.5 seconds. Both
elapsed_time and universal_time are simple structs with sec_ and nsec_ exposed data
members representing seconds and nanoseconds. In the case of universal_time, this is the
number of seconds and nanoseconds since midnight Jan. 1, 1970. The universal_time
default constructor returns the current time. So the above example could have also been
written as in Alternate example of timed_lock() usage .
Listing: Alternate example of timed_lock() usage
void foo()
{
Metrowerks::timed_mutex::scoped_timed_lock lock(foo_mut, false);
Metrowerks::elapsed_time time_out(1, 500000000);
Metrowerks::universal_time now;
if (lock.timed_lock(now + time_out))
{
// got the lock
}
else
{
// do something else
}
}
In general you can add and subtract and compare universal_time and elapsed_time as makes
sense.
In single thread mode, all locks will lock their mutexes and return immediately (times are
ignored). However, if you try to lock a lockedmutex, or unlock an unlockedmutex, then an
exception of type Metrowerks::lock_error (derived from std::exception) will be thrown (even
in single thread mode).
27.3 Threads
void join();
A default constructed thread object represents the current thread. You can create a new
thread of execution by passing a general function object, or a simple function pointer. In
either case, the function must take no parameters and return void. When a thread
destructs, it "detaches" the thread of execution (to use Posix-threads terminology). Once
this happens, the thread is independent. You will no longer be able to refer to it, and it
will clean up after itself when it terminates. But should main terminate before the thread
does, the program ends anyway. You can have one thread wait on another with the join()
member function.
Listing: Example of join() function
#include <ewl_thread>
#include <iostream>
void do_something()
{
std::cout << "Thread 1!
}
int main()
{
Metrowerks::thread t1(do_something);
t1.join();
}
In the above example, main will wait for (join with) t1. Note that global objects like
std::cout must be protected if more than one thread is going to access it. You must do this
work yourself.
Listing: Example of protecting threads
#include <ewl_thread>
#include <iostream>
Metrowerks::mutex cout_mutex;
void do_something()
{
Metrowerks::mutex::scoped_lock lock(cout_mutex);
std::cout << "Thread 1!
}
void do_something_else()
int main()
{
std::cout << "Main
Metrowerks::thread t1(do_something);
Metrowerks::thread t2(do_something_else);
t1.join();
t2.join();
}
In this example, each thread locks cout_mutex before using cout. main() didn't have to lock
cout because no other threads started until after main() was done with cout.
You can also have threads sleep, but using a mutex and/or a condition variable (described
in Condition Variables ) is almost always a better solution. Similarly for thread::yield
which is really just a convenience function for calling sleep with elapsed_time(0).
In single thread mode, creating a thread is equivalent to a synchronous function call
(though not nearly as efficient).
If you have multiple threads to create, you can create a Metrowerks::thread_group.
Listing: Example of thread_group
class thread_group
{
public:
thread_group();
~thread_group();
const thread* create_thread(const thread::func_type& f);
void join_all();
};
The main feature of thread_group is that it makes it very easy to join with all of the threads.
Listing: Example of joining threads
int main()
{
std::cout << "Main
Metrowerks::thread_group g;
g.create_thread(do_something);
g.create_thread(do_something_else);
g.join_all();
}
A condition variable is a way for two threads to signal each other based on some
predicate, such as a queue being empty or full. This is represented by Metrowerks::condition.
void notify_one();
void notify_all();
template <typename ScopedLock> void wait(ScopedLock& lock);
};
It is up to some other thread to make I_need_more_data false, and it will likely need to lock
some_mutex in order to do it. When it does, it should execute one of:
cond.notify_one();
or
cond.notify_all();
It must also unlock some_mutex to allow the other thread's wait to return. But it does not
matter whether some_mutex gets unlocked before or after the notification call. Once the
original wakes from the wait, then the signal is satisfied. Should it wait again, then
another thread will have to renotify it.
If it is more convenient, you can pass a predicate to the wait function, which will then do
the while loop for you. Note that there are also several timed waits if you want to limit
the sleep time (which can be thought of as an additional "condition" on the system clock).
Example of condition usage is a full example of condition usage. One thread puts stuff
into a queue while another thread reads stuff back out of the other end.
Listing: Example of condition usage
#include <iostream>
#include <queue>
#include <ewl_thread>
class unbounded_queue
{
public:
typedef Metrowerks::mutex Mutex;
typedef Mutex::scoped_lock Lock;
void send (int m);
int receive();
private:
std::queue<int> the_queue_;
Metrowerks::condition queue_is_empty_so_;
Mutex mut_;
};
if (the_queue_.size() == 1)
queue_is_empty_so_.notify_one();
}
int unbounded_queue::receive()
{
Lock lock(mut_);
while (the_queue_.empty())
queue_is_empty_so_.wait(lock);
int i = the_queue_.front();
std::cout << "received: " << i << '
the_queue_.pop();
return i;
}
unbounded_queue buf;
void sender()
{
int n = 0;
while (n < 1000)
{
void receiver()
{
int n;
do
{
n = buf.receive();
} while (n >= 0);
}
int main()
{
Metrowerks::thread send(sender);
Metrowerks::thread receive(receiver);
send.join();
receive.join();
}
In the above example one thread continually sends data to a std::queue, while another
thread reads data out of the queue. The reader thread must wait if the queue is empty, and
the sender thread must notify the reader thread (to wake up) if the queue changes from
empty to non-empty.
An interesting exercise is to transform the above example into a "bounded queue". That is,
there is nothing from stopping the above example's queue from sending all of the data
before the receiver thread wakes up and starts consuming it.
Example of queue limitation is an example if you wanted to limit the above queue to a
certain number of elements (like 20).
Listing: Example of queue limitation
#include <iostream>
#include <cdeque>
#include <ewl_thread>
class bounded_queue
{
public:
private:
Queue the_queue_;
Metrowerks::condition queue_is_empty_so_;
Metrowerks::condition queue_is_full_so_;
Mutex mut_;
};
private:
const C& c_;
};
private:
const C& c_;
};
int bounded_queue::receive()
{
Lock lock(mut_);
queue_is_empty_so_.wait(lock,
container_not_empty<Queue>(the_queue_));
int i = the_queue_.front();
std::cout << "received: " << i << '
if (the_queue_.size() == the_queue_.capacity())
queue_is_full_so_.notify_one();
the_queue_.pop_front();
return i;
}
bounded_queue buf(20);
void sender()
{
int n = 0;
while (n < 1000)
{
buf.send(n);
++n;
}
buf.send(-1);
}
void receiver()
{
int n;
do
{
n = buf.receive();
} while (n >= 0);
}
int main()
{
Metrowerks::thread send(sender);
Metrowerks::thread receive(receiver);
send.join();
The above example actually demonstrates more than was advertised. Not only does it
limit the queue length to 20, it also introduces a non-std container (Metrowerks::cdeque)
which easily enables the monitoring of maximum queue length. It also demonstrates how
more than one condition can be associated with a mutex. And furthermore, it uses the
predicate versions of the wait statements so that explicit while loops are not necessary for
the waits. Note that the predicates are negated: the wait will loop until the predicate is
true.
Condition variablesare fairly dangerous in single threaded code. They will compile and do
nothing. But note that you may loop forever waiting for a predicate that won't change:
while (the_queue.empty())
queue_not_empty.wait(lk);
If the_queue.empty() is true then this is just an infinite loop in single thread mode. There is
no other thread that is going to make the predicate false.
27.5 call_once
Every once in a while, you need to make sure a function is called exactly once. This is
useful for initialization code for example.
The concept is similar to a local static, but local statics are not thread safe. It is possible
two threads might try to construct a local static at once, before the initialization flag gets
set.
Listing: Example two trheads constructing a static
Metrowerks::mutex&
get_mutex()
{
static Metrowerks::mutex mut; // ??!!!!
return mut;
}
If more than one thread can call get_mutex() for the first time, at the same time, then it is
possible that two threads may try to construct mut (and this would be bad). There are a
couple of ways to deal with this problem.
You could make mut a global. But that may give you an undefined order of construction
among global objects that is unacceptable for your application's start up code.
You could call get_mutex() once before you create any threads:
int main()
{
get_mutex(); // just initialize the local static
}
Now it is safe to call get_mutex() from multiple threads as the construction step is already
done.
Simple, but a little ugly. And you may not have control over main (what if you're writing
a library?).
Enter Metrowerks::call_once. You can use call_once to ensure that only one thread calls
get_mutex for the first time. The prototype for call_once looks like:
Metrowerks::once_flag is the type of flag that you must initialize (at link time) to the macro:
_EWL_THREAD_ONCE_INIT.
If call_once is called with such a flag, it will atomically execute the function, and set the
flag to some other value. All other threads attempting to call call_once will block until the
first call returns. Later threads calling into call_once with the same flag will return without
doing anything. Here is how you could use it to "initialize" get_mutex().
Listing: Example of initializing using get_mutex()
Metrowerks::mutex&
get_mutex_impl()
{
static Metrowerks::mutex mut;
return mut;
}
void init_get_mutex()
{
get_mutex_impl();
}
Metrowerks::mutex&
get_mutex()
{
Metrowerks::call_once(init_get_mutex, init_get_mutex_flag);
return get_mutex_impl();
}
The first thread into get_mutex will also go into call_once while blocking other threads from
getting past that point. It then constructs the static mutex at its leisure. Once it returns,
then threads can have unfettered access to the fully constructed static mutex.
call_once works identically in single thread mode.
EWL C++ Library Reference Manual, Rev. 10.x, 02/2014
Freescale Semiconductor, Inc. 639
thread_specific_ptr
27.6 thread_specific_ptr
You can have as many thread_specific_ptr's as you want, and pointing to whatever type
you desire. The thread_specific_ptr is not copyable or assignable, but you can assign a
pointer to it.
Listing: Example of assigning a pointer
thread_specific_ptr<int> my_data;
...
my_data.reset(new int(3));
From then on, the thread that called reset can access that data like:
std::cout << *my_data;
*my_data = 4;
// etc.
You can release the memory with my_data.release(). This transfers pointer ownership back
to you, so you must then delete the pointer. But you need not call release just to prevent
memory leaks. thread_specific_ptr will automatically delete its data. And you can put in a
new pointer by calling reset again. thread_specific_ptr will make sure the original pointer
gets properly deleted. Do not use the array form of new with thread_specific_ptr. It will be
using delete to free your pointer.
Listing: Example of freeing a pointer
Metrowerks::thread_specific_ptr<int> value;
void increment()
{
++*value;
}
Metrowerks::mutex cout_mutex;
void thread_proc()
{
value.reset(new int(0));
for (int i = 0; i < 1000; ++i)
increment();
Metrowerks::mutex::scoped_lock lock(cout_mutex);
std::cout << *value << '
}
int main()
{
Metrowerks::thread_group threads;
for (int i = 0; i < 5; ++i)
threads.create_thread(&thread_proc);
thread_proc();
threads.join_all();
}
1000
1000
1000
1000
1000
Once for main, and once for the five threads. Note how no locking is necessary in
accessing the "global" thread_specific_ptr. It is as if each thread has its own local copy of
this global.
The C++ standards committee is currently considering what will go into the next C++
standard. Several proposals have been voted into a Technical Report for considertion and
the Embedded Warrior Library for C++ has some of these items in namespace std::tr1.
#define _EWL_TR1_NAMESPACE 0
28.2.1 result_of
The template class result_of defines a nested typedef named type, that is the return type
of the function type in result_of's template parameter.
Listing: Class result_of synopsis
Namespace std::tr1{
template <class Sig>
class result_of
{
public:
typedef /* implementation details */ type;
};
28.2.2.1 get_result_type
A nested typedef named type, that is the return type of the function type in result_of's
template parameter.
typedef /* implementation details */ type; ();
Remarks
This can be used to specify the operator within function objects that have multiple
signatures. result_of is typically used in template programming (as opposed to just
determining the return type).
Listing: Example usage of template class result_of
namespace std::tr1{
#include <functional>
#include <iostream>
#include <typeinfo>
result
double
bool
See Also
Class type_info
28.3.1 reference_wrapper
Remarks
You can pass reference_wrapper's around, and even put them into containers.
The reference_wrapper also serves as a marker for some packages that explicitly look for
it, and behave differently when they find it. For example if you send a reference_wrapper
to the function make_tuple, a T& will be put in the tuple instead of a T or a
reference_wrapper<T>. See see the description of tuple for more details.
28.3.2.1 ref
See Also
Reference_wrapper, cref()
28.3.2.2 cref
See Also
Reference_wrapper, ref()
Remarks
This is a highly generic and powerful "call back" mechanism that includes function
pointers, member function pointers, and arbitrary function objects while maintaining
similar syntax and semantics to function pointers.
Listing: Class Synopsis
Namespace std::tr1 {
Stuff
}
28.4.1.1 Constructor
Initializes the mutex object.
mutex ();
mutex(const mutex&);
The assignment operator is declared private and not defined to prevent the mutex object
from being copied.
28.4.1.2 Destructor
Used for implicit mutex destruction.
~mutex ();
Remarks
Destroys the mutex object.
Listing: Example of class usage
#include <vector>
#include <utility>
#include <functional>
#include <iostream>
#include <cassert>
struct compare_and_record
values.push_back(std::make_pair(x, y));
return x == y;
};
int main()
f = &add;
f = std::minus<int>();
g = &adjacent;
compare_and_record car;
g = std::tr1::ref(car);
28.4.2.1 Member_function
Description.
void prototype();
// do some stuff
int main()
result
double
bool
These template shared pointer classes are included in the header <memory>.
Its overhead is a little higher than you might be used to, but there are so many handy
features (a lot of them safety features) that this pointer is hard to resist. See the proposal
for a list of features (which include safety across DLL boundaries).
The shared_ptr works closely with weak_ptr, where weak_ptr takes the place of a raw
pointer to break cyclic references. Again see the proposal for many more details and
motivation.
This package follows closely from boost::shared_ptr, and has all of the latest
improvements from that implementation.
Listing: Class Synopsis
Namespace std::tr1 {
Stuff
}
28.6.1.1 Constructor
Initializes the mutex object.
mutex ();
mutex(const mutex&);
The assignment operator is declared private and not defined to prevent the mutex object
from being copied.
28.6.1.2 Destructor
Used for implicit mutex destruction.
~mutex ();
Remarks
Destroys the mutex object.
Listing: Example of class usage
Namespace std::tr1 {
#include <iostream>
// do some stuff
int main()
{
}
result
double
bool
28.6.2.1 Member_function
Description.
void prototype();
int main()
{
result
double
bool
28.7 Template class T0, class T1, ... class T9 class tuple
The header <tuple> exposes a std::pair-like class which generalizes the pair concept up to
10 members.
This proposal lives in two headers: <tuple> and <tupleio>. It closely follows these two
proposals:
Remarks
int main()
int i = 0;
i = 2;
28.7.1.1 Constructor
Initializes the mutex object.
mutex ();
mutex(const mutex&);
The assignment operator is declared private and not defined to prevent the mutex object
from being copied.
28.7.1.2 Destructor
Used for implicit mutex destruction.
~mutex ();
Remarks
Destroys the mutex object.
NOTE
<tupleio> has been preserved. You must include this header to
get the I/O abilities. This allows <tuple> to remain much
smaller. tuples of different sizes can be compared (==, <, etc.)
with the obvious semantics. tuple_like types can be compared
with each other.
Listing: Example of<codeph> tuple </codeph>class usage
#include <tuple>
#include <string>
#include <utility>
int main()
{
std::pair<int, double> p(1, 2.0);
std::tr1::tuple<long, short, std::string> t(1, 2, "hi");
bool b = p < t;
}
/* The tuples implemented here are interoperable with your own tuple_like types (should
you create any).
The tuple I/O manipulators:
tuple_open
tuple_close
tuple_delimiter
take both charT arguments and const charT* arguments. Thus you can specify multi-
character braces or delimeters. This can come in handy when dealing with tuples of
std::string:
*/
if (!s.fail())
std::cout << t << '\n';
else
std::cout << "failed\n";
}
( Hi , 5 )
/*And finally, if the TR is put into namespace std (instead of std::tr1)
<tupleio> extends I/O ability to other tuple_like types such as std::pair.
*/
#define _EWL_TR1_NAMESPACE 0
#include <tupleio>
#include <string>
#include <iostream>
#include <map>
int main()
{
typedef std::map<std::string, int> Map;
Map m;
m["one"] = 1;
m["two"] = 2;
m["three"] = 3;
(one 1)
(three 3)
(two 2)
28.7.2.1 Member_function
Description.
void prototype();
Remarks
If
Listing: Example of class usage
Namespace std::tr1 {
#include <iostream>
// do some stuff
int main()
{
result
double
bool
The bind library is a new library voted into the first Library Technical Report.
As such, it is placed in namespace std::tr1. It is not standard, but is considered
"interesting" by the C++ committee. It may become standardized in the future. This is a
generalization of the existing std::bind1st and std::bind2nd functions.
The bind library consists of a series of overloaded template functions which when called
will return an implementation defined function object that can then be evaluated. The
purpose of bind is to adapt one function to another expected signature, or to combine
simpler functions into a more complex functor. It is found in the new header <bind>. This
implementation supports functions with up to 10 arguments.
Listing: Synopsis of the bind library
namespace std { namespace tr1 {
// 0 argument functors
// details
bind(F f);
// details
bind(F f);
// details
bind(R (*f)());
// 1 argument functors
// details
bind(F f, A1 a1);
// details
bind(F f, A1 a1)
// details
// details
// details
// details
// 2 argument functors
// details
// details
template <class R, class B1, class B2, class A1, class A2>
// details
// details
// details
...
// 9 argument functors
template <class F, class A1, class A2, class A3, class A4, class A5,
// details
template <class R, class F, class A1, class A2, class A3, class A4,
// details
template <class R, class B1, class B2, class B3, class B4, class B5,
class A1, class A2, class A3, class A4, class A5,
// details
bind(R (*f)(B1, B2, B3, B4, B5, B6, B7, B8, B9),
template <class R, class T, class B1, class B2, class B3, class B4,
class A1, class A2, class A3, class A4, class A5,
// details
bind(R (T::*f)(B1, B2, B3, B4, B5, B6, B7, B8), A1 a1, A2 a2, A3 a3,
template <class R, class T, class B1, class B2, class B3, class B4,
// details
} } // std::tr1
There are bind functions that accept a function-like object as the first argument, and then
from 0 to 9 arguments. The return type of the functor can be explicitly supplied as the
first template argument, or not. When not supplied, it is deduced. If the functor is a
function pointer or member pointer, the return type is deduced from that signature. If the
functor is a class with a nested type called result_type, the return type is deduced as
F::result_type.
If the functor is a member pointer, then the first argument to the resulting functor must be
a reference, pointer or smart pointer to an object containing the pointed to member. That
first argument must be supplied to bind either explicitly, or implicitly as another bind
expression, or a placeholder (examples will follow).
The bind overloads taking a functor with no arguments and do not accept member
pointers, as member pointer functors must have at least one argument for the reference or
pointer to the object.
The bind overloads taking from 1 thru 9 arguments include overloads for a function-like
class, function pointers, and member function pointers.
The bind overloads taking a single argument (in addition to the functor) include an
overload for taking a pointer to member data. Thus you can create a functor out of a
pointer to pair<T1, T2>::first (for example).
Listing: Simple use of std::bind2nd example
#include <vector>
#include <functional>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <iostream>
int main()
random_shuffle(v.begin(), v.end());
copy(v.begin(), i, out);
6 3 5 7 10 1 9 8 4 2
2 3 4 1
with:
Obviously bind is not a big win over bind2nd in this example. This example is meant to
introduce bind by comparing it with the presumably well known std::bind2nd. Further
examples will show how bind goes beyond the limitations of bind1st and bind2nd.
The #include <bind> is needed to bring std::tr1::bind into scope. As bind is a library
technical report item, it lives in namespace std::tr1 instead of in namespace std.
The "_1" notation is new. The _1 is called a placeholder, it's full name is
std::tr1::placeholders::_1. You can just say using namespace std::tr1::placeholders; to bring
just the placeholders into scope without bringing everything else into scope. The _1 is a
signal to the functor returned from bind to substitute the first argument used when calling
the functor object into the place indicated by the position of the _1. That is:
bind1st(f, x);
is equivalent to:
bind(f, x, _1);
Both functions return a unary functor F such that F(y) calls f(x, y). In the bind example,
_1 is the placeholder for y that the client will supply to F.
You can also turn f(x, y) into a function that takes no arguments by simply not using any
placeholders:
Additionally there are more placeholders: _1, _2, _3, ... _9. You can use these
placeholders to simply reorder the arguments to a function:
And of course bind can handle functions (f) with a number of arguments ranging from 0
to 9. You must ensure that for every parameter of f there is a matching argument in the
bind expression. Except that when f is a member function pointer, then there must be an
additional argument in the bind expression, as the first argument represents the object (or
a pointer to the object).
Imagine a class type Employee and the desire to sort by the member function number()
which returns the Employee ID:
class Employee
{
public:
int number() const;
};
...
std::sort(v.begin(), v.end(),
bind(std::less<int>(),
bind(&Employee::number, _1),
bind(&Employee::number, _2)
)
);
The member function number is converted into a functor: once for the first argument, and
once for the second argument to sort's compare predicate. Then those two bind
expressions are composed as arguments to std::less<int>. Without bind you would have
to write a custom binary compare predicate for this situation (or operator< for Employee).
Note that if you change Employee to:
class Employee
{
public:
int number;
};
then the predicate developed above for sorting does not change.
private:
int n_chips_;
float diameter_;
};
We've got a container of cookies and we need to erase all those cookies that either have
too few chips, or are too small in diameter:
v.end()
);
Note that the above continues to work whether our container holds Cookie, Cookie*, or
some smart_ptr<Cookie>.
28.8.3 function
When used in conjunction with std::tr1::function, you can store the bind expression
indefinitely, and then execute it at the proper time. For example, here is a crude runtime-
configurable menu example:
#include <vector>
#include <functional>
#include <bind>
struct Document
{
Document() {}
Document* close() {delete this; return 0;}
Document* save() {return this;}
Document* print() {return this;}
private:
Document(const Document&);
Document& operator=(const Document&);
};
int main()
{
// declare menu structure
std::vector<std::tr1::function<Document* ()> > menu(5);
Document* current_doc = 0;
using std::tr1::bind;
using std::tr1::ref;
menu[1] = &Document::open;
If in the above example, an argument needed to be sent to all of the callbacks (or 2 or 3
arguments), that could easily be handled with placeholders:
Document* print(const std::string& printer_name)
{... return this;} ...
menu[4] = bind(&Document::print, ref(current_doc), _1);...
current_doc = menu[4]("color printer");
So bind is really handy. And when combined with the existing algorithms in <algorithm>
and <numeric>, or when combined with the new std::tr1::function, bind becomes
ultimately flexible, and absolutely indispensable.
The EWL header <ewlconfig> contains a description of the macros and defines that are
used as switches or flags in the EWL C++ library.
The EWL C++ library has various flags that may be set to customize the library to users
specifications.
• _CSTD
• _Inhibit_Container_Optimization
• _Inhibit_Optimize_RB_bit
• _EWL_DEBUG
• __ewl_error
• _EWL_ARRAY_AUTO_PTR
• _EWL_CFILE_STREAM
• __EWL_CPP__
• _EWL_EXTENDED_BINDERS
• _EWL_EXTENDED_PRECISION_OUTP
• _EWL_FORCE_ENABLE_BOOL_SUPPORT
• _EWL_FORCE_ENUMS_ALWAYS_INT
• _EWL_IMP_EXP
• __EWL_LONGLONG_SUPPORT__
• _EWL_MINIMUM_NAMED_LOCALE
• _EWL_NO_BOOL
• _EWL_NO_CONSOLE_IO
• _EWL_NO_CPP_NAMESPACE
• _EWL_NO_EXCEPTIONS
• _EWL_NO_EXPLICIT_FUNC_TEMPLATE_ARG
• _EWL_NO_FILE_IO
• _EWL_NO_IO
• _EWL_NO_LOCALE
• _EWL_NO_REFCOUNT_STRING
• _EWL_NO_VECTOR_BOOL
• _EWL_NO_WCHART
• _EWL_NO_WCHART_LANG_SUPPORT
• _EWL_NO_WCHART_C_SUPPORT
• _EWL_NO_WCHART_CPP_SUPPORT
• _EWL_POSIX_STREAM
• _EWL_WIDE_FILENAME
• _EWL_WFILEIO_AVAILABLE
• _STD
29.1.1 _CSTD
The _CSTD macro evaluates to ::std if the EWL C library is compiled in the std
namespace, and to nothing if the EWL C library is compiled in the global namespace.
_STD and _CSTD are meant to prefix C++ and C objects in such a way that you don't have to
care whether or not the object is in std or not. For example:
_STD::cout, or _CSTD::size_t.
29.1.2 _Inhibit_Container_Optimization
If this flag is defined it will disable pointer specializations in the containers. This may
make debugging easier.
You must recompile the C++ lib when flipping this switch.
29.1.3 _Inhibit_Optimize_RB_bit
Normally the red/black tree used to implement the associative containers has a space
optimization that compacts the red/black flag with the parent pointer in each node (saving
one word per entry). By defining this flag, the optimization is turned off, and the red/
black flag will be stored as an enum in each node of the tree.
29.1.4 _EWL_DEBUG
This switch when enabled and the library is rebuilt will put EWL Standard C++ library
into debug mode. For full information see Overview of EWL C++ Debug Mode .
You must recompile the C++ lib when flipping this switch.
29.1.5 __ewl_error
This feature is included for those wishing to use the C++ lib with exceptions turned off.
In the past, with exceptions turned off, the lib would call fprintf and abort upon an
exceptional condition. Now you can configure what will happen in such a case by filling
out the definition of __ewl_error().
29.1.6 _EWL_ARRAY_AUTO_PTR
When defined auto_ptr can be used to hold pointers to memory obtained with the array
form of new. The syntax looks like:
auto_ptr<string, _Array<string> >
pString(new string[3]);
pString.get()[0] = "pear";
pString.get()[1] = "peach";
pString.get()[2] = "apple";
Without the _Array tag, auto_ptr behaves in a standard fashion. This extension to the
standard is not quite conforming, as it can be detected through the use of template
arguments.
This extension can be disabled by not defining _EWL_ARRAY_AUTO_PTR.
29.1.7 _EWL_CFILE_STREAM
Set when the file system does not support wide character streams.
29.1.8 __EWL_CPP__
Evaluates to an integer value which represents the C++ lib's current version number. This
value is best when read in hexidecimal format.
29.1.9 _EWL_EXTENDED_BINDERS
Defining this flag adds defaulted template parameters to binder1st and binder2nd. This
allows client code to alter the type of the value that is stored. This is especially useful
when you want the binder to store the value by const reference instead of by value to save
on an expensive copy construction.
Listing: Example:
#include <string>
#include <functional>
#include <algorithm>
struct A
{
public:
A(int data = 0) : data_(data) {}
friend bool operator < (const A& x, const A& y) {return x < y;}
private:
int data_;
A(const A&);
};
int main()
{
using namespace std;
A a[5];
A* i = find_if(a, a+5, binder2nd<less<A> >(less<A>(), A(5)));
}
This causes the compile-time error, because binder2nd is attempting to store a copy of
A(5). But with _EWL_EXTENDED_BINDERS you can request that binder2nd store a const A& to A(5).
A* i = find_if(a, a+5,
binder2nd<less<A>, const A&>(less<A>(), A(5)));
This also allows for the use of polymorphic operators by specifying reference types for
the operator.
This extension to the standard is detectable with template parameters so it can be disabled
by not defining _EWL_EXTENDED_BINDERS.
29.1.10 _EWL_EXTENDED_PRECISION_OUTP
When defined this allows the output of floating point output to be printed with precision
greater than DECIMAL_DIG. With this option, an exact binary to decimal conversion can be
performed (by bumping precision high enough).
The cost is about 5-6Kb in code size.
You must recompile the C++ lib when flipping this switch.
29.1.11 _EWL_FORCE_ENABLE_BOOL_SUPPORT
And the C++ lib will link instead of getting the ctype link error.
Changing this flag will require a recompile of the C++ library.
29.1.12 _EWL_FORCE_ENUMS_ALWAYS_INT
29.1.13 _EWL_IMP_EXP
The C, C++, SIOUX and runtime shared libraries have all been combined into one shared
library located under the appropriate OS support folder in your CodeWarrior installation
path.
The exports files ( .exp) have been removed. The prototypes of objects exported by the
shared lib are decorated with a macro:
_EWL_IMP_EXP_xxx
_EWL_IMP_EXP_CPP
_EWL_IMP_EXP_SIOUX
_EWL_IMP_EXP_RUNTIME
Define these macros to nothing if you don't want to import from the associated lib,
otherwise they will pick up the definition of _EWL_IMP_EXP.
There is a header <UseDLLPrefix.h> that can be used as a prefix file to ease the use of the
shared lib. It is set up to import all 4 sections.
There is a problem with non-const static data members of templated classes when used in
a shared lib. Unfortunately <locale> is full of such objects. Therefore you should also
define _EWL_NO_LOCALE which turns off locale support when using the C++ lib as a shared
lib. This is done for you in <UseDLLPrefix.h>. See _EWL_NO_LOCALE for more details.
29.1.14 __EWL_LONGLONG_SUPPORT__
When defined, C++ supports long long and unsigned long long integral types. Recompile
the C++ lib when flipping this switch.
29.1.15 _EWL_MINIMUM_NAMED_LOCALE
When defined, turns off all of the named locale stuff except for "C" and "" (which will be
the same as "C"). This reduces both lib size and functionality, but only if you are already
using named locales. If your code does not explicitly use named locales, this flag has no
effect.
29.1.16 _EWL_NO_BOOL
If defined then bool will not be treated as a built-in type by the library. Instead it will be a
typedef to unsigned char (with suitable values for true and false as well). If
_EWL_FORCE_ENABLE_BOOL_SUPPORT is not defined then this flag will set itself according to the "
Enable bool support" switch in the language preference panel.
29.1.17 _EWL_NO_CONSOLE_IO
This flag allows you to turn off console support while keeping memory mapped streams
( stringstream) functional.
See Also
_EWL_NO_FILE_IO
29.1.18 _EWL_NO_CPP_NAMESPACE
If defined then the C++ lib will be defined in the global namespace.
You must recompile the C++ lib when flipping this switch.
29.1.19 _EWL_NO_EXCEPTIONS
If defined then the C++ lib will not throw an exception in an exceptional condition.
Instead void __ewl_error(const char*); will be called. You may edit this inline in
<ewlconfig> to do whatever is desired. Sample implementations of __ewl_error are
provided in <ewlconfig>.
Remarks
The operator new (which is in the runtime libraries) is not affected by this flag.
This flag detects the language preference panel "Enable C++ exceptions" and defines
itself if this option is not on.
The C++ lib must be recompiled when changing this flag (also, if the language preference
panel is changed).
29.1.20 _EWL_NO_EXPLICIT_FUNC_TEMPLATE_ARG
When defined, assumes that the compiler does not support calling function templates
with explicit template arguments.
On Windows, when "Legacy for-scoping" is selected in the language preference panel,
then this switch is automatically turned on. The Windows compiler goes into a MS
compatible mode with ARM on.
This mode does not support explicit function template arguments. In this mode, the
signatures of has_facet and use_facet change.
You must recompile the C++ lib when flipping this switch.
Listing: Example of_EWL_NO_EXPLICIT_FUNC_TEMPLATE_ARG usage:
Standard setting:
template <class Facet>
29.1.21 _EWL_NO_FILE_IO
This flag allows you to turn off file support while keeping memory mapped streams
(stringstream) functional.
See Also
_EWL_NO_CONSOLE_IO
29.1.22 _EWL_NO_IO
If this flag is defined, C++ will not support any I/O (not even stringstreams).
29.1.23 _EWL_NO_LOCALE
When this flag is defined, locale support is stripped from the library. This has tremendous
code size benefits.
All C++ I/O will implicitly use the "C" locale. You may not create locales or facets, and
you may not call the imbue method on a stream. Otherwise, all streams are completely
functional.
The C++ lib must be recompiled when flipping this switch.
29.1.24 _EWL_NO_REFCOUNT_STRING
The flag _EWL_NO_REFCOUNT_STRING is deprecated and will have no effect (it is harmless). This
rewrite has higher performance and lower code size compared to previous releases.
29.1.25 _EWL_NO_VECTOR_BOOL
If this flag is defined it will disable the standard vector<bool> partial specialization. You
can still instantiate vector<bool>, but it will not have the space optimization of one bool
per bit.
There is no need to recompile the C++ lib when flipping this switch, but you should
remake any precompiled headers you might be using.
29.1.26 _EWL_NO_WCHART
29.1.27 _EWL_NO_WCHART_LANG_SUPPORT
This flag is set if the compiler does not recognize wchar_t as a separate data type (no
wchar_t support in the language preference panel). The C++ lib will still continue to
support wide character functions. wchar_t will be typedef'd to another built-in type.
The C++ library must be recompiled when turning this switch on (but not when turning it
off).
29.1.28 _EWL_NO_WCHART_C_SUPPORT
This flag is set if the underlying C lib does not support wide character functions. This
should not be set when using EWL C.
The C++ library must be recompiled when turning this switch on (but not when turning it
off).
29.1.29 _EWL_NO_WCHART_CPP_SUPPORT
This flag can be set if wide character support is not desired in the C++ lib. Setting this
flag can cut the size of the I/O part of the C++ lib in half.
The C++ library must be recompiled when turning this switch on (but not when turning it
off).
29.1.30 _EWL_POSIX_STREAM
Set when a POSIX based library is being used as the underlying C runtime library.
29.1.31 _EWL_WIDE_FILENAME
If the flag _EWL_WIDE_FILENAME is defined, then the file stream classes support wide character
filenames (null terminated arrays of const wchart_t*). Each stream class has an overloaded
constructor, and an overloaded open member taking the const wchar_t. If the underlying
system supports wide filenames, EWL C++ will pass the wchar_t straight through without
any locale encoding.
Thus the interpretation of the wide filename is done by the OS, not by the C++ library. If
the underlying system does not support wide filenames, the open will fail at runtime.
By default _EWL_WIDE_FILENAME is not defined as these signatures are not standard.
Turning on this flag does not require a recompile of EWL C++.
When EWL C is not being used as the underlying C library, and when the file stream is
implemented in terms of FILE* (see _EWL_CFILE_STREAM ), the system is said to not
support wide filenames and the open will fail at runtime.
When using Posix as the underlying implementation (see _EWL_POSIX_STREAM ),
wide filenames are supported if the Posix library comes from the EWL Extras Library (in
which case the _EWL_WFILEIO_AVAILABLE flag must be on).
29.1.32 _EWL_WFILEIO_AVAILABLE
Set when a wide character file name is available for a file name.
29.1.33 _STD
This macro evaluates to ::std if the C++ lib is compiled in the std namespace, and to
nothing if the C++ lib is compiled in the global namespace.
SeeAlso
_CSTD
Index
adjacent_find 325
__EWL_CPP__ 668 advance 306
__ewl_error 667 Algorithms 125
__EWL_LONGLONG_SUPPORT__ 671 alloc_ptr 594
_CSTD 666 allocate 121
_EWL_ARRAY_AUTO_PTR 667 allocator_type 569
_EWL_CFILE_STREAM 668 allocator members 121
_EWL_CX_LIMITED_RANGE 375 Allocator Requirements 104
_EWL_DEBUG 667 always_noconv 192
_EWL_EXTENDED_BINDERS 668 am_pm 230
_EWL_EXTENDED_PRECISION_OUTP 669 any 299
_EWL_FORCE_ENABLE_BOOL_SUPPORT 669 append 148
_EWL_FORCE_ENUMS_ALWAYS_INT 670 apply 358
_EWL_IMP_EXP 670 Arbitrary-Positional Stream 58
_EWL_MINIMUM_NAMED_LOCALE 671 arg 384
_EWL_NO_BOOL 672 Arithmetic operations 109
_EWL_NO_CONSOLE_IO 672 array_size 591
_EWL_NO_CPP_NAMESPACE 672 Array Forms 84
_EWL_NO_EXCEPTIONS 672 Assertions 100
_EWL_NO_EXPLICIT_FUNC_TEMPLATE_AR assign 136, 148, 275, 277, 285
G 673 Assignment 573
_EWL_NO_FILE_IO 674 Assignment Operator 143, 353
_EWL_NO_IO 674 Assignments 141
_EWL_NO_LOCALE 674 Associative Containers 287
_EWL_NO_REFCOUNT_STRING 674 at 147
_EWL_NO_VECTOR_BOOL 674 atexit 82
_EWL_NO_WCHART 675 auto_ptr 126, 129–132
_EWL_NO_WCHART_C_SUPPORT 675 auto_ptr_ref 132
_EWL_NO_WCHART_CPP_SUPPORT 675
_EWL_NO_WCHART_LANG_SUPPORT 675
_EWL_POSIX_STREAM 676 B
_EWL_RAW_ITERATORS 321
_EWL_WFILEIO_AVAILABLE 676 back_insert_iterator 311
_EWL_WIDE_FILENAME 676 Back_insert_iterator Operators 311
_Inhibit_Container_Optimization 666 back_inserter 312
_Inhibit_Optimize_RB_bit 666 bad 429
_STD 677 bad_alloc 86
<cmath> 373 Bad_alloc 86
<cstdlib> 373 bad_cast 89
<sstream> 511 bad_exception 92
bad_typeid 90
base 307
A basic_filebuf::close 531
basic_filebuf::imbue 534
Abnormal Termination 93 basic_filebuf::is_open 529
abort 82 basic_filebuf::open 530
abrev_monthname 229 basic_filebuf::overflow 532
abrev_weekday 229 basic_filebuf::pbackfail 532
abs 383 basic_filebuf::seekoff 533
Access 576 basic_filebuf::seekpos 533
accumulate 370 basic_filebuf::setbuf 533
Adaptors 116, 117 basic_filebuf::showmanyc 531
Addition Operator 143 basic_filebuf::sync 534
address 121 basic_filebuf::underflow 532
adjacent_difference 372
X
xalloc 414