...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Safe Numerics |
This policy is used to promote safe types in arithmetic expressions according to the rules in the C++ standard. But rather than using the native C++ standard types supported by the compiler, it uses types whose length in number of bits is specified by the template parameters.
This policy is useful for running test programs which use C++ portable integer types but which are destined to run on an architecture which is different than the one on which the test program is being built and run. This can happen when developing code for embedded systems. Algorithms developed or borrowed from one architecture but destined for another can be tested on the desktop.
Note that this policy is only applicable to safe types whose base type is a type fulfilling the type requirements of Integer.
Parameter | Type | Description |
---|---|---|
C |
int | Number of bits in a char |
S |
int | Number of bits in a short |
I |
int | Number of bits in an integer |
L |
int | Number of bits in a long |
LL |
int | Number of bits in a long long |
Consider the following problem. One is developing software which uses a very small microprocessor and a very limited C compiler. The chip is so small, you can't print anything from the code, log, debug or anything else. One debugs this code by using the "burn" and "crash" method - you burn the chip (download the code), run the code, observe the results, make changes and try again. This is a crude method which is usually the one used. But it can be quite time consuming.
Consider an alternative. Build and compile your code in testable modules. For each module write a test which exercises all the code and makes it work. Finally download your code into the chip and - voilà - working product. This sounds great, but there's one problem. Our target processor - in this case a PIC162550 from Microchip Technology is only an 8 bit CPU. The compiler we use defines INT as 8 bits. This (and a few other problems), make our algorithm testing environment differ from our target environment. We can address this by defining INT as a safe integer with a range of 8 bits. By using a custom promotion policy, we can force the evaluation of C++ expressions in the test environment to be the same as that in the target environment. Also in our target environment, we can trap any overflows or other errors. So we can write and test our code on our desktop system and download the code to the target knowing that it just has to work. This is a huge time saver and confidence builder. For an extended example on how this is done, look at Safety Critical Embedded Controller .