cpp / expert
Snippet
Semantic Safety via Strong Type Templates
This pattern uses templates to wrap primitive data types in unique classes based on a 'Tag' type. This prevents accidental implicit conversions and logical errors, such as swapping width and height parameters in function calls, which the compiler cannot otherwise detect.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T, typename Tag>class StrongType {public:explicit StrongType(T const& value) : value_(value) {}T& get() { return value_; }T const& get() const { return value_; }private:T value_;};struct WidthTag {};struct HeightTag {};using Width = StrongType<double, WidthTag>;using Height = StrongType<double, HeightTag>;void setDimensions(Width w, Height h) {}
Breakdown
1
template <typename T, typename Tag>
Declares a template that takes the underlying data type and a phantom tag type to ensure uniqueness.
2
explicit StrongType(T const& value)
The explicit keyword prevents the compiler from performing unintended implicit conversions from the base type.
3
using Width = StrongType<double, WidthTag>;
Creates a concrete type for Width that is distinct from any other double-based StrongType at compile time.