C++ User-Defined Literals | Custom Suffixes for Units and DSLs
이 글의 핵심
User-defined literals let you write `5_km` or `10_MB` with type-safe, often constexpr-friendly conversions.
Basic syntax
Illustrates integer, floating, and string literal operators with examples like _km, _pi, "hello"_upper.
Standard literals
using namespace std::chrono_literals, string_literals, complex_literals—5s, "hi"s, 1.0 + 2.0i, etc.
Practical examples
- Distance units —
operator"" _m,_km,_mireturning aDistancetype. - Byte sizes —
_KB,_MB,_GB. - Angles —
_deg,_rad. - Colors — parse
"#FF0000"_rgbintoColor.
Raw literals
Template operator"" _bin() for compile-time parsing—advanced usage.
Common pitfalls
- User suffixes must start with
_(reserved space without underscore). - Match literal kinds: integer vs floating vs string—mismatch causes compile errors.
- Mark literal operators
constexprwhen you need compile-time results.
Overload set
constexpr T operator"" _suffix(unsigned long long); // integral
constexpr T operator"" _suffix(long double); // floating
T operator"" _suffix(const char*, size_t); // string
template<char...> T operator"" _suffix(); // raw
FAQ
When: units, small DSLs, type-safe constants.
Cost: constexpr operators fold away at compile time.
Standard literals: s for std::string, chrono suffixes, complex suffixes.
Placement: define in a namespace and using selectively.
Related posts
- Chrono
- Tuple guide
Keywords
C++, user-defined literals, operators, C++11, DSL.
See also
- ADL
async& launch- Atomic operations