std::flip is a little-known utility from the C++ standard library header <functional>: it is a higher-order function that accepts a Callable and returns an equivalent Callable with the order of its parameters reversed (or “flipped”). To understand how it can be useful, let’s start with a simple example. Consider the following tree node class: struct node { int value; node* parent = nullptr; node* left_child = nullptr; node* right_child = nullptr; }; Let’s write a function that takes two nodes, and returns whether the first node is a parent of the second one, at any level of ancestry: bool is_ancestor_of(node const* maybe_parent, node const* maybe_child) { if (maybe_child == nullptr || maybe_parent == nullptr) { return false; } while (maybe_child->parent != nullptr) { if (maybe_child->parent == maybe_parent) { return true; } maybe_child = maybe_child->parent; } return false; } This is basically walking up the tree from the child node as if it were a linked list. The reverse operation either implies walking through two children nodes, or simply flipping the order of parameters, which is where std::flip intervenes: auto is_descendant_of = std::flip(is_ancestor_of); // This property should always hold assert(is_descendant_of(node1, node2) == is_ancestor_of(node2, node1)); Origins std::flip finds its roots in functional programming, a domain in which it is extremely prevalent: Haskell has flip in its Prelude module. PureScript has flip in its Prelude module. OCaml has flip in the Fun module of its standard library. Idris has flip in its Prelude module. Elm used to have flip in its Basics module. It got removed, but lots of polyfills still provide it. The LISP family of languages generally does not provide such a function by default, but the need is common enough that I have seen programmers online wonder how often it gets reimplemented manually. Functional programming libraries in lots of other programming languages also generally oblige: Boost.Hana has boost::hana::flip...
First seen: 2025-09-29 18:34
Last seen: 2025-09-30 06:36