The C++ Type System Is Your Friend 2016
The C++ Type System Is Your Friend 2016
Friend
Hubert Matthews
[email protected]
Why this talk?
C Machine Language
types types what this talk is
focused on
meters m = 3.4;
seconds s = 1.5;
auto velocity = m + s; // oops, probably meant / not +
// but it still compiles
feet f = 5.6;
meters m2 = m + f; // physical units correct but
// measurement system wrong
Year y = 2016_yr;
#include <utility>
using namespace std::rel_ops; // defines <=,>=,>,!=
int main() {
Year y1(7), y2(5);
assert(y1 > y2); // true
}
int main() {
auto velocity = 23.1_meters / 1.5_secs;
• A
// auto error = 23.1_meters + 1.5_secs; // compile-time error
}
Copyright © 2016 Oxyware Ltd 19/39
Physical quantities and dimensions
• Allows us to define operations that convert
types (here the dimension exponents are
calculated to give new dimension values)
• Prevents physically impossible calculations
• Prevents mixing of measurement units (e.g.
mixing SI Units and imperial units)
• Can be used for related “flavours” of types,
such as multiple currencies that are “the same
underlying thing” but with different units
template <>
struct op_traits<Year> {
static constexpr bool add_scalar = true;
};
int main() {
Year y1{10}, y2{5};
//auto y3 = y1 + y2; // compiler error
auto y3 = y1 + 2;
}
struct NonNegChecker {
constexpr NonNegChecker(float f) {
if (f < 0) throw std::invalid_argument("oops!");
}
};
Resource management
Destructors Most operations
Cleanup should be explicit
Rollback
Client
OO planned
Interface
whitelist
Server
templates Tmpl<T>
Tmpl<X> ad hoc
concepts
X