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

Proof that you can do more!

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...>;

std::variant<int, float> intFloat { 0.0f };
std::visit(overload(
    [](const int& i) { ... },
    [](const float& f) { ... },
  ),
  intFloat;
);

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

It’s just two lines of compact C++ code, but it packs a few interesting concepts.

Let’s see how this thing works and go through the three new C++17 features that enable this one by one.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.