Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Overloaded Operations and Conversions Based on *C++ Primer, 5th ed.*, Chapter 14: Overloaded Operations and Conversions, this post summarizes design principles for operator overloading, implementation idioms for major operators, **Functors** `operator()`, `std::function`, and conversion operators `operator TYPE()`. ## 1. Operator Overloading Fundamentals & Member vs. Nonmember Guidelines Overloaded operators are functions named with the `operator` keyword followed by the operator symbol (`operator+`, `operator=`, `operator()`, etc.). - **Four Operators That Cannot Be Overloaded:** Scope resolution `::`, member selection `.`, [pointer-to-member dereference `.*`]({{< relref "/programming/cpp/primer/pointers-to-class-member.md" >}}) — whereas `*` and `->*` *can* be overloaded, and the ternary conditional `?:` operator cannot be overloaded. - **Operators You Should Not Overload:** Overloading logical AND (`&&`), logical OR (`||`), or the comma operator (`,`) loses built-in **short-circuit evaluation** and **order-of-evaluation guarantees**, so they should not be overloaded. The unary address-of operator (`&`) should also not be overloaded for class types. ### Choosing Member (`this`) vs. Nonmember (`friend`) Implementation | Category | Target Operators | Rationale & Core Rules | | :--- | :--- | :--- | | **Must Be Member** | **`=` (assignment), `[]` (subscript), `()` (call), `->` (member access arrow)** | Required by the C++ language standard to be declared **exclusively as member functions** (declaring them as nonmembers is a compile error). | | **Should Be Member** | **`+=`, `-=`, `*=` (compound assignment)**
**`++`, `--` (increment/decrement), `*` (dereference)** | Directly mutate the object's state or are unary operations tightly bound to the class type. | | **Should Be Nonmember**
`friend` if needed | **`+`, `-`, `*`, `/` (arithmetic)**
**`==`, `!=`, `<`, `>` (equality/relational)**
**`<<`, `>>` (I/O streams)** | **Symmetry & Left-Hand Implicit Conversion:** A member operator requires the left-hand operand to be `*this`. If `operator+` were a member of `std::string`, `STRING_INSTANCE + "hi"` would work, but **`"hi" + STRING_INSTANCE` would fail to compile because the left operand is `const char*`**! Defining symmetric operators as nonmembers allows implicit conversions on both left and right operands equally. | --- ## 2. Implementation Idioms by Operator | Operator | Signature Pattern | Key Implementation Rules | | :--- | :--- | :--- | | **Output (`<<`)** | `ostream& operator<<(ostream &os, const CLASS &x);` | Must be a **nonmember function** — defining it as a member of `CLASS` cannot match the `cout << CLASS_INSTANCE` syntax. Minimize formatting and return `os`. | | **Input (`>>`)** | `istream& operator>>(istream &is, CLASS &x);` | Nonmember function. **Input can fail at runtime, so always check `if (is)` after reading**, and if it fails, reset `x = CLASS();` to leave the object in a valid default state. | | **Arithmetic (`+`) vs. Compound (`+=`)** | `CLASS& CLASS::operator+=(const CLASS &rhs);`
`CLASS operator+(const CLASS &lhs, const CLASS &rhs);` | Implement `operator+=` as a member function first, then implement nonmember `operator+` by copying `lhs`, delegating to `+= rhs`, and returning by value `CLASS`. | | **Subscript (`[]`)** | `ELEM& operator[](size_t n);`
`const ELEM& operator[](size_t n) const;` | Always define **both non-`const` and `const` versions**. This allows modifying elements on non-const objects while still reading elements on `const` objects. | | **Prefix vs. Postfix (`++`, `--`)** | **Prefix:** `CLASS& operator++();`
**Postfix:** `CLASS operator++(int);` | Postfix takes an **unused dummy `int` parameter** solely to distinguish its signature from prefix. Prefix returns an lvalue reference `CLASS&` to the incremented `*this`; postfix saves a copy of the old state, calls `++*this`, and returns the old copy by value `CLASS`. | | **Member Access (`*`, `->`)** | `T& operator*() const;`
`T* operator->() const;` | Used in smart pointers and iterators. For an object `CLASS_INSTANCE`, `CLASS_INSTANCE->MEMBER` is evaluated as `(CLASS_INSTANCE.operator->())->MEMBER`, so `operator->()` must return a raw pointer or another object that defines `operator->`. | ```cpp // Prefix vs. Postfix Increment Implementation class Ptr { public: Ptr& operator++() { // Prefix (++p): increment and return reference to *this ++curr; return *this; } Ptr operator++(int) { // Postfix (p++): dummy int parameter! Save old state, call prefix, return old copy Ptr ret = *this; ++*this; // Reuse prefix operator++ return ret; } private: int *curr; }; ``` --- ## 3. Function-Call Operator `operator()` and Functors When a class overloads the function-call operator `operator()`, instances of that class can be invoked like functions. Such classes are called **Function Objects** or **Functors**. - Unlike ordinary functions, a functor is a **class and can store internal state in member variables** across calls. - When the compiler encounters a **lambda expression**, it translates the lambda into an unnamed functor class — a closure class — with an overloaded `operator() const` and creates a temporary instance of it; see [Lambda Expressions]({{< relref "/programming/cpp/primer/lambda.md" >}}). ```cpp struct AbsInt { int operator()(int val) const { return val < 0 ? -val : val; } }; AbsInt absObj; // Create an instance of the functor class int ui = absObj(-42); // Calls absObj.operator()(-42) -> returns 42 ``` ### Passing a Functor: `<>` Template Type Argument vs. `()` Function Call Argument The core principle when passing a comparator functor is that **`<>` template arguments expect a type**, whereas **`()` function arguments expect an instance**: | Aspect | `<>` Template Type Argument | `()` Function Call Argument | | :--- | :--- | :--- | | **Target Passed** | **Functor class type itself** — `std::greater`, no `()` | **Functor instance** — `std::greater()`, requires `()` to construct a temporary | | **Typical Usage** | Container declarations — `priority_queue`, `set`, `map` | Algorithm function calls — `sort`, `find_if`, etc. | | **Passing a Lambda Directly** | ❌ A lambda expression is an **instance** of an anonymous class, not a type, so it cannot go directly inside `<>` — bind it to a variable, pass `decltype` to `<>`, and pass the variable to the constructor `()` | ✅ Expects an **instance**, so an inline lambda expression can be passed directly inside `()` | ```cpp // 1. Container <> template type argument (std::priority_queue) // (a) Functor class: pass the type itself inside <> without () std::priority_queue, std::greater> pq1; // (b) Lambda: bind to a variable, pass decltype to <>, and pass the variable to the constructor auto cmp = [](int a, int b) { return a > b; }; std::priority_queue, decltype(cmp)> pq2(cmp); // 2. Algorithm () function call argument (std::sort) // Parameter expects an object, so pass a temporary functor () or inline lambda directly std::vector v = {3, 1, 2}; std::sort(v.begin(), v.end(), std::greater()); std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; }); ``` --- ## 4. Callable Objects and `std::function` C++ has **four kinds of callable objects** that can be invoked like functions: 1. Ordinary functions 2. Function pointers 3. Lambda expressions — instances of anonymous functor classes 4. Objects of functor classes that define `operator()` Although these four have completely distinct C++ types, they can share the same **call signature** — return type and parameter types, such as `int(int, int)`. To store heterogeneous callables with the same call signature in a single container such as an operator dispatch `map`, use **`std::function`** from ``: ```cpp #include #include #include int add(int i, int j) { return i + j; } // 1. Ordinary function auto mod = [](int i, int j) { return i % j; }; // 2. Lambda (anonymous functor instance) struct Div { int operator()(int i, int j) { return i / j; } }; // 3. Functor class // Different underlying types, but all share the call signature int(int, int)! std::map> binops = { {"+", add}, // Function pointer {"-", std::minus()}, // Standard library functor instance {"/", Div()}, // User-defined functor instance {"*", [](int i, int j) { return i * j; }}, // Inline lambda instance {"%", mod} // Named lambda instance }; int r1 = binops["+"](10, 5); // 15 int r2 = binops["*"](10, 5); // 50 ``` --- ## 5. Conversion Operators `operator TYPE() const` and `explicit` - **Converting Constructor `CLASS(OTHER_TYPE)`:** Converts another type `OTHER_TYPE` **into a `CLASS` object** — see [Classes: `explicit`]({{< relref "/programming/cpp/primer/classes.md#3-implicit-class-type-conversions-and-explicit" >}}). - **Conversion Operator `operator TYPE() const`:** Special member functions such as `operator int() const` and `operator bool() const` that convert **a `CLASS` object into another type**. - Must be a member function; because the operator name itself names the return type, **specify no separate return type, leave the parameter list empty, and generally mark it `const`**. ### Dangers of Implicit Conversion and `explicit` Conversion Operators (C++11) Non-explicit conversion operators often trigger surprising silent conversions in arithmetic expressions. C++11 introduced **`explicit` conversion operators** to require an explicit cast (`static_cast(obj)`). - **The Contextual `bool` Exception — `explicit operator bool() const`:** - Even when a conversion operator to `bool` is marked `explicit`, **the compiler automatically applies it in condition contexts** — `if`, `while`, and `for` conditions, logical operators `!`, `&&`, `||`, and the ternary `?:` condition! - **Canonical Example — `std::istream` (`std::cin`):** - The standard library's `std::istream` defines `explicit operator bool() const`. If `std::istream` instead had a non-`explicit` `operator bool()`, a reversed-arrow typo like **`std::cin << 42;` would implicitly convert `cin` to `bool` (`0` or `1`) and silently compile as the integer bit-shift `1 << 42`**. - Marking it `explicit operator bool() const` rejects `std::cin << 42;` at compile time while still allowing `while (std::cin >> VAR)` to convert the returned `std::istream&` to `bool` automatically in the loop condition — see [IO Library: Evaluating Stream State]({{< relref "/programming/cpp/primer/io-library.md#3-input-loop-patterns-while-is--num-vs-while-iseof" >}}). ```cpp class SmallInt { public: SmallInt(int i = 0) : val(i) {} // explicit conversion operator: blocks silent int conversion, allows static_cast explicit operator int() const { return val; } // explicit bool conversion: blocks arithmetic conversion, but auto-applies in if/while conditions! explicit operator bool() const { return val != 0; } private: int val; }; SmallInt si = 3; // si + 3; // Compile error! explicit operator int() blocks silent conversion int x = static_cast(si) + 3; // OK: explicit cast is allowed if (si) { /* ... */ } // OK! Condition context automatically invokes explicit operator bool() ```