2 Lines Of Code and 3 C++17 Features - The Overload Pattern -- Bartlomiej Filipek

2023-10-02_15-16-38.pngLearn how the overload pattern works for std::variant visitation and how it changed with C++20 and C++23.

2 Lines Of Code and 3 C++17 Features - The Overload Pattern

By Bartlomiej Filipek

From the article:

While I was doing research for my book and blog posts about C++17 several times, I stumbled upon this pattern for visitation of std::variant:

template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; 
template<class... Ts> overload(Ts...) -> overload<Ts...>; 

With the above pattern, you can provide separate lambdas “in-place” for visitation.

It’s just two lines of compact C++ code but packs some exciting techniques.

Let’s see how this works and go through the three new C++17 features that make this pattern possible.

Changelog

  • Updated on 18th Septeber 2023: C++23 updates, and Compiler Explorer examples.
  • Updated on 13th January 2020: better description for the whole article and C++ 20 features were mentioned - CTAD for aggregates.
  • Initial version on 11th Feb 2019

Intro

The code mentioned at the top of the article forms a pattern called overload (or sometimes overloaded), and it’s primarily valid for std::variant visitation.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.