C++ User-Defined Literals | Custom Suffixes for Units and DSLs

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_literals5s, "hi"s, 1.0 + 2.0i, etc.

Practical examples

  1. Distance unitsoperator"" _m, _km, _mi returning a Distance type.
  2. Byte sizes_KB, _MB, _GB.
  3. Angles_deg, _rad.
  4. Colors — parse "#FF0000"_rgb into Color.

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 constexpr when 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.


  • Chrono
  • Tuple guide

Keywords

C++, user-defined literals, operators, C++11, DSL.

See also

  • ADL
  • async & launch
  • Atomic operations