liveBook · Manning

Whole value idiom

As explained in Learn C++ by Example

The whole value idiom represents a meaningful quantity, including its associated semantics or unit, with a lightweight type rather than a bare primitive value.

The whole value idiom represents a meaningful quantity with a lightweight type instead of a bare primitive. The type carries semantics such as a calendar unit and helps ensure that arguments appear in the correct order. section 4.1

A typed calendar date

std::chrono::year_month_day requires an std::chrono::year, std::chrono::month, and std::chrono::day. Passing a month where a day is expected produces a compiler error, catching the mistake early and precisely. section 4.1

Listing 4.1 Creating a specific date
auto new_years_eve = std::chrono::year_month_day(
   std::chrono::year(2022),
   std::chrono::month(12),
   std::chrono::day(31)
);

Create New Year’s Eve by passing explicitly typed year, month, and day values. section 4.1

How Learn C++ by Example covers it

How deep it goes
Explains typed parameters, compiler diagnostics, and quantity semantics, but stops short of implementing a custom value type.
Examples
Uses std::chrono::year_month_day to construct New Year’s Eve before converting it into a day-based time point.
What you can do after
Apply it via std::chrono to construct correctly typed dates and detect swapped calendar arguments at compile time.
How it connects
Connects whole values with quantity patterns, std::chrono, calendar dates, durations, and time points.

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.