How do you declare a C++ user-defined literal so that 10_usd creates a Money, and which parameter types may it take?
answer
- operator, two quotes, a suffix
- underscore or reserved
- unsigned long long for integers
- lives in a literals namespace
basics
~20 sDeclare a namespace-scope literal operator such as Money operator""_usd(unsigned long long). Integer literals arrive as unsigned long long, floating literals as long double, or as const char* for the raw spelling. Suffixes without a leading underscore are reserved for the standard.
solid answer
~50 sA **user-defined literal** (C++11) is a literal followed by a suffix, and the compiler turns `10_usd` into a call to a **literal operator**: `Money operator""_usd(unsigned long long dollars)`. The parameter list is fixed by the standard: `unsigned long long` for integer literals, `long double` for floating literals, `const char*` for a raw literal operator that sees the spelling, a character type for character literals, and a pointer plus `std::size_t` for string literals; a template with a `char` pack is also allowed. The suffix must start with an underscore; suffixes without one, such as `s`, `sv` and `ms`, are reserved for the standard library. Declare it in a namespace such as `billing::literals` and bring it in with `using namespace`. Since C++23 the spelling with a space, `operator"" _usd`, is deprecated, and since C++20 a `consteval` literal operator can reject an overflowing amount at compile time.
code
cpp · 20 lines#include <climits>
#include <cstdio>
namespace billing {
struct Money { long long cents; };
inline namespace literals {
consteval Money operator""_usd(unsigned long long dollars) {
if (dollars > static_cast<unsigned long long>(LLONG_MAX / 100))
throw "amount too large"; // not a constant expression: compile error
return Money{static_cast<long long>(dollars) * 100};
}
} // namespace literals
} // namespace billing
int main() {
using namespace billing::literals;
constexpr billing::Money fee = 10_usd;
std::printf("%lld\n", fee.cents); // 1000
}go deeper
Recognise the operator""_usd syntax and that integer literals arrive as unsigned long long.
Explain the allowed parameter lists, the underscore rule, why the operator sits in a literals namespace, and what -10_usd really means.
Show how consteval rejects overflow at compile time and why a raw literal operator is the exact choice for decimal money.
Decide whether units such as currency deserve literals in a codebase, weighing visible units at call sites against namespaces to import and overloads to maintain.
## What a user-defined literal is C++11 lets a literal carry a **ud-suffix**: `10_usd`, `2.5_usd`, `"abc"_tag`. The compiler rewrites each one into a call to a **literal operator**, a namespace-scope function whose name is `operator""` followed by the suffix: ```cpp Money operator""_usd(unsigned long long dollars); Money m = 10_usd; // calls operator""_usd(10ULL) ``` The standard library uses the same feature: `"text"s` gives a `std::string`, `"text"sv` a `std::string_view`, and `250ms` a `std::chrono::milliseconds`. Its chrono operators come in exactly the pair a money type needs, one taking `unsigned long long` and one taking `long double`. ## Which parameter lists are allowed A literal operator must have one of the parameter lists the standard enumerates, and no default arguments: | Literal | Parameter list | |---|---| | integer (`10_usd`) | `unsigned long long`, or the raw form `const char*` | | floating (`2.5_usd`) | `long double`, or the raw form `const char*` | | character (`'x'_c`) | `char`, `wchar_t`, `char8_t`, `char16_t` or `char32_t` | | string (`"x"_tag`) | a pointer to the character type plus `std::size_t` | | numeric template | `template <char...>` with an empty parameter list | Anything else is rejected: `Money operator""_eur(int)` gives clang's `invalid literal operator parameter type 'int', did you mean 'unsigned long long'?`. ## Rules that interviewers probe 1. **Underscore.** Suffixes that do not start with `_` are reserved for future standardization. Clang warns that such an operator will never be invoked by a literal. 2. **No space.** The form `operator"" _usd`, with a space before the suffix, is deprecated since C++23; clang warns `identifier '_usd' preceded by whitespace in a literal operator declaration is deprecated`. 3. **Namespace scope.** A literal operator must belong to a namespace, though it may be declared as a friend. Put it in a nested namespace such as `billing::literals` (often an `inline namespace`, as the standard library does) and write `using namespace billing::literals;` where literals are used. Without that, `10_usd` fails with `no matching literal operator`. 4. **No negative literals.** `-10_usd` is unary minus applied to the `Money` that `10_usd` produced. It needs a `Money operator-() const`; without one, clang reports `invalid argument type 'Money' to unary expression`. ## How the compiler picks the operator The standard looks up the literal operator by **unqualified lookup**, without argument-dependent lookup, which is why the `using` directive is needed. Then, for an integer literal such as `10_usd`: 1. If an operator taking **`unsigned long long`** is found, the literal becomes `operator""_usd(10ULL)`. 2. Otherwise it needs **either** a raw literal operator (`const char*`), which receives the characters `"10"`, **or** a numeric literal operator template, which receives them as template arguments, but not both. A floating literal follows the same steps with `long double` in place of `unsigned long long`. An integer literal never falls back to the `long double` operator: with only that one declared, `10_usd` fails with `no matching literal operator`, so a money type that accepts both `10_usd` and `2.5_usd` needs both overloads. ## Making the literal safe Two choices separate a toy literal from one fit for a billing service: - **Reject overflow at compile time.** `10_usd` multiplies by 100, which can overflow `long long` for a huge literal. Declaring the operator **`consteval`** (C++20) forces evaluation during compilation, and a `throw` on the overflow path makes such a literal a compile error. The code example shows the pattern; the overflowing literal gives `call to consteval function 'operator""_usd' is not a constant expression`. - **Avoid binary floating point for cents.** `2.5_usd` through a `long double` parameter rounds through binary fractions. A raw literal operator (`const char*`) or a numeric literal operator template receives the digits as written and can parse them exactly. ## Is it worth it? A literal suffix makes units visible at the call site (`fee = 10_usd`) and removes a class of mistakes where a bare number means cents in one place and dollars in another. The cost is a namespace to import and a few overloads to maintain.
- Why put operator""_usd in a nested literals namespace?Literal operators are found by ordinary unqualified lookup, so they must be visible where the literal is written. A dedicated namespace lets code import just the literals with `using namespace billing::literals;` instead of the whole library namespace, which is the pattern the standard library follows.
- How would you make 19.99_usd exact?Use a raw literal operator, `Money operator""_usd(const char* digits)`, or a numeric literal operator template, and parse the digits yourself. A `long double` parameter receives a binary floating value, so 19.99 is already rounded before your code sees it.
- A literal operator for 10_usd can take an int parameter
- -10_usd passes a negative number to the literal operator
- Any identifier can be a suffix, underscore or not
- A literal operator can be a non-static member of Money
- A literal operator in a nested namespace is found without a using-directive
Assumes C++23: user-defined literals are C++11, consteval literal operators need C++20, and the operator"" _usd spelling with a space is deprecated since C++23.