This shows you the differences between two versions of the page.
|
dss:laboratoare:06 [2019/07/01 14:43] eduard.staniloiu [Mixins] |
dss:laboratoare:06 [2019/07/01 15:29] (current) eduard.staniloiu [Exercises] |
||
|---|---|---|---|
| Line 243: | Line 243: | ||
| ==== Exercises ==== | ==== Exercises ==== | ||
| + | |||
| + | === 1. checkedint === | ||
| + | |||
| + | We want to define a **struct CheckedInt** that defines facilities for efficient checking of integral operations against overflow, casting with loss of precision, unexpected change of sign, etc. **CheckedInt** must work with both built-in integral types and other **CheckedInt**s. | ||
| + | |||
| + | CheckedInt offers encapsulated integral wrappers that do all checking internally and have configurable behavior upon erroneous results. For example, **CheckedInt!int** is a type that behaves like int but aborts execution immediately whenever involved in an operation that produces the arithmetically wrong result. | ||
| + | |||
| + | The declaration should look something like | ||
| + | <code d> | ||
| + | struct Checked(T, Hook) | ||
| + | </code> | ||
| + | |||
| + | In order to work with built-in types, you need to define: opAssign, opBinary, opBinaryRight, opCast, opCmp, opEquals, opOpAssign, opUnary. | ||
| + | |||
| + | CheckedInt has customizable behavior with the help of a second type parameter, Hook. Depending on the Hook type, core operations on the underlying integral may be verified for overflow or completely redefined. Implement the following predefined hooks: | ||
| + | - **Abort** : fails every incorrect operation with a message to std.stdio. stderr followed by a call to assert(0). It is the default second parameter, i.e. Checked!short is the same as Checked!(short, Abort). | ||
| + | - **Throw** : fails every incorrect operation by throwing an exception. | ||
| + | - **Warn**: prints incorrect operations to std.stdio.stderr but otherwise preserves the built-in behavior. | ||
| + | |||
| + | |||
| + | |||
| + | |||