Implementing variant Visitation Using Lambdas

By Vittorio Romeo

The addition of std::variant to the upcoming C++17 standard will introduce a "type-safe sum type" to the STL. Given a set of types, std::variant (and boost::variant) model an ADT ("algebraic data type") where only one of them can be active: they essentially are a type-safe "tagged union".

The interface they provide, however, is more cumbersome than it needs to be and doesn’t lend itself to monadic composition. Defining exhaustive visitors requires the user to create a class with several operator() overloads, or to create a chain of if constexpr(…​) calls. Both solutions are not very elegant.

After a brief overview of std::variant and its usefulness, this talk will focus on the implementation of a "lambda-based in-place visitation" approach, where the user can visit a variant by simply providing a set of overloaded lambdas on the spot.

Don’t be fooled, though - the implementation will not be as simple as it sounds. The talk will cover:

  • Traditional non-recursive variant visitation.

  • Lambda-based non-recursive variant visitation.

    • The implementation of an "overload set" generator will be analyzed.

  • Traditional recursive variant visitation.

  • Lambda-based recursive variant visitation.

    • The implementation of a "Y-Combinator" will be analyzed and benchmarked against std::function.

    • Callable object arity deduction techniques will be implemented and applied to make the user interface more elegant.

This talk is intended for an audience familiar with C++11 and C++14 core language features.