Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 171 ยท Modern C++ and Beyond

User-Defined Literals

Learn C++ user-defined literals - write operator"" suffixes for units and types, raw and template forms, naming rules, and use std::literals such as s, sv, ms and i.

You already write literals with suffixes without thinking about it: 10u is an unsigned int, 3.5f is a float, 100ULL is an unsigned long long. C++11 lets you invent your own suffixes. A user-defined literal (UDL) turns 90_deg, 5_km or "hello"_id into a function call that returns whatever type you choose, so a number can carry its unit and the compiler can tell a distance from a duration.

The standard library already uses them: "text"s makes a std::string, "text"sv a std::string_view, 250ms a std::chrono::milliseconds. In this lesson you'll write literal operators for integers, floating-point numbers and strings, learn the raw and template forms for when you need the exact digits, see why suffixes must start with an underscore, and use the library's std::literals namespaces correctly. You'll need functions, constexpr and a little operator overloading background.

The shape of a literal operator

A literal operator is a function named operator"" followed by the suffix. The function receives the literal's value and returns anything:

C++
constexpr double operator""_km(long double kilometers) {
    return static_cast<double>(kilometers) * 1000.0;     // store everything in meters
}

double d = 2.5_km;    // calls operator""_km(2.5L)  ->  2500.0

The parameter type is not free. For a numeric literal the compiler passes the value in the widest type of its kind, so the allowed forms are:

Literal looks like Parameter type
42_x (integer) unsigned long long
4.2_x (floating-point) long double
'a'_x char (also wchar_t, char8_t, char16_t, char32_t)
"abc"_x const char*, std::size_t (the text and its length)

A negative number is not part of the literal: in -5_km, the unary minus applies to the result of 5_km. That is why integer literal operators take an unsigned parameter.

C++ Units in the type system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Providing both an integer and a floating-point overload, as above, lets users write 5_m and 5.5_m. The two spellings are different literal kinds: if you define only the long double version, 5.5_m works but 5_m is an error ("unable to find numeric literal operator"). Define both when both spellings make sense.

Because the result is a distinct type (Meters, not double), mixing units by accident is a compile error. That is the main reason to write UDLs: not shorter syntax, but safer code.

Naming rules

  • Your suffix must start with an underscore: _km, _id, _deg. Suffixes without a leading underscore are reserved for the standard library (s, sv, ms, i, h).
  • Don't put a space between operator"" and the suffix in new code: operator""_km. The older spelling operator "" _km still works but is deprecated since C++23.
  • Underscore followed by an uppercase letter, such as _Km, is reserved for the implementation. Use lowercase suffixes.
  • Literal operators are ordinary functions, so they live in a namespace. Put them in a nested namespace literals and let users opt in with a using namespace directive, exactly as the standard library does. A global using namespace in a header would make every user pay for them.

String literals

For a string literal the operator receives the characters and the length, so it never needs strlen and handles embedded zeros:

C++ A string literal operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The using namespace text_literals; inside main is the opt-in. Without it, "section"_tag would not find the operator.

Raw and template literal operators

Sometimes the long double that arrives is too lossy, or you want to check the digits yourself. Two more forms exist for numeric literals.

A raw literal operator takes the literal's characters as written, as a const char* terminated by '\0':

C++
unsigned parse_binary(const char* digits);   // your own helper

constexpr unsigned operator""_bin(const char* digits) { return parse_binary(digits); }

A numeric literal operator template receives each character as a non-type template argument, so you can validate the literal at compile time and reject bad input with a compile error:

C++ Compile-time checked literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Here 1011_b is lexed as the integer 1011, then handed to the template as Digits = '1','0','1','1'. Uncommenting the last line fails at compile time because throw is not allowed in a constant expression that is evaluated.

If you define several forms for the same suffix, the compiler prefers the cooked form (unsigned long long or long double), then the raw form, then the template form.

Literals in the standard library

The standard library defines its UDLs in nested namespaces of std::literals. Each one is reachable with using namespace std::literals; or with the narrower name:

Suffix Namespace Result Example
s std::literals::string_literals std::string "abc"s
sv std::literals::string_view_literals std::string_view "abc"sv
h, min, s, ms, us, ns std::literals::chrono_literals std::chrono::duration 250ms, 1.5h
y, d (C++20) chrono_literals std::chrono::year, std::chrono::day 2026y, 15d
i, if, il std::literals::complex_literals std::complex 3.0 + 4.0i

Notice that s means seconds after a number and std::string after a quoted string; the compiler tells them apart by the literal's kind. Because the standard's suffixes never start with an underscore, using namespace std::literals; cannot clash with your own suffixes.

C++ The standard literals in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The difference between "abc" and "abc"s matters. Without the suffix you get a const char[4] that decays to a pointer, and "a" + "b" doesn't compile (you can't add pointers). With the suffix, "a"s + "b" works. See std::string_view for why sv avoids copies and Time with std::chrono for the duration types.

Common mistakes

  • Forgetting the underscore. operator""km compiles with a warning at best, and the suffix can never be used by well-formed code; use _km.
  • Expecting the suffix to be found without using. Operators in a namespace need a using-directive at the call site.
  • Providing only long double. Then 5_m fails; add the unsigned long long overload.
  • Using UDLs for everything. A suffix is worth it for units, identifiers and tags. For ordinary constructions, a plain constructor is clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a user-defined literal suffix start with?

    Suffixes that don't start with an underscore are reserved for the standard library, so your own suffixes, such as _km or _id, begin with one.
  2. 2. Which parameter type does a literal operator for 42_x receive when you define the usual cooked form?

    Integer literals are passed as unsigned long long (and floating-point ones as long double). A leading minus is a separate unary operator applied to the result.
  3. 3. What is the difference between "hi" and "hi"s?

    The s suffix after a string literal comes from std::literals::string_literals and creates a std::string. After a number it means seconds in the chrono literals.
  4. 4. Why would you write a literal operator template template <char... C> operator""_b()?

    The template form gives you every character of the literal as a template argument, so a constexpr evaluation can reject invalid input with a compile error.
  5. 5. Where should you normally define your own literal operators?

    Literal operators are ordinary namespace-scope functions. A dedicated namespace, as in std::literals, lets users choose to import them.

Summary

  • A user-defined literal calls operator""_suffix and can return any type, which lets numbers carry units or meaning.
  • Numeric operators take unsigned long long or long double; character and string forms take the character, or the pointer plus length.
  • Raw (const char*) and template (template <char...>) forms see the digits as written, and the template form can validate them at compile time.
  • Your suffixes must start with an underscore; plain suffixes belong to the standard library.
  • Keep operators in a namespace and import them with using namespace; the standard offers s, sv, ms, h, i and more under std::literals.

Next: Modern C++ Features by Standard, a tour of what each standard added.