cpp / expert
Snippet
Strongly Typed Opaque Wrappers via Phantom Types
Expert-level type safety technique using 'Phantom Types' to wrap primitive data. It creates distinct types from the same underlying representation (e.g., int), preventing accidental assignment or comparison between semantically different identifiers like User IDs and Account IDs.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T, typename Tag>struct Opaque {explicit Opaque(T val) : value(val) {}T value;bool operator==(const Opaque& other) const { return value == other.value; }};struct UserIdTag {};struct AccountIdTag {};using UserId = Opaque<int, UserIdTag>;using AccountId = Opaque<int, AccountIdTag>;void process(UserId u) { /* ... */ }
Breakdown
1
template <typename T, typename Tag>
Declares a template where 'Tag' is the phantom type used only for differentiation.
2
explicit Opaque(T val)
The explicit keyword prevents implicit conversion from the raw type to the wrapper.
3
using UserId = Opaque<int, UserIdTag>;
Defines a unique type for User IDs that cannot be mixed with Account IDs.