Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

User-defined literals

Use case

Readable size constans without manual multiplication.

Explanation

User-defined literals let us write 64_KB instead of 64 * 1024. The _ prefix is required.

Code

#include <iostream>

constexpr size_t operator""_KB(unsigned long long kb) { return kb * 1024; }

constexpr size_t operator""_MB(unsigned long long mb) {
  return mb * 1024 * 1024;
}

int main() {

  size_t stackSize = 8_MB;
  size_t pageSize = 4_KB;

  std::cout << "Stack size: " << stackSize << " bytes.\n";
  std::cout << "Page size: " << pageSize << " bytes.\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/user-defined-literals
Stack size: 8388608 bytes.
Page size: 4096 bytes.