Tech News
← Back to articles

`std::flip`

read original related products more articles

std::flip is a little-known utility from the C++ standard library header : 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.

... continue reading