cpp / expert
Snippet
Dimensional Type Safety using Template Parametrization
This snippet uses template metaprogramming and std::ratio to enforce dimensional analysis at compile-time. By defining datatypes that carry their physical dimensions (Mass, Length, Time), the compiler prevents logical errors like adding distance to time.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <ratio>template <typename T, typename Mass, typename Length, typename Time>struct Quantity {T value;template <typename M2, typename L2, typename T2>auto operator+(const Quantity<T, M2, L2, T2>& other) const {static_assert(std::is_same_v<Mass, M2> && std::is_same_v<Length, L2> && std::is_same_v<Time, T2>,"Incompatible units!");return Quantity<T, Mass, Length, Time>{value + other.value};}};using Meters = Quantity<double, std::ratio<0>, std::ratio<1>, std::ratio<0>>;using Seconds = Quantity<double, std::ratio<0>, std::ratio<0>, std::ratio<1>>;
Breakdown
1
static_assert(std::is_same_v<Mass, M2> ... "Incompatible units!");
Validates that the dimensions of two quantities match before allowing addition, preventing unit errors.
2
using Meters = Quantity<double, std::ratio<0>, std::ratio<1>, std::ratio<0>>;
Defines a concrete type for meters where the Length dimension is set to 1 and others to 0.