C++26: a placeholder with no name

submited by
Style Pass
2025-01-08 18:00:29

Let’s continue exploring C++26. In this post, we are going to discuss a core language feature proposed by Corentin Jabot and Micheal Park in P2169R4. With the new standard we get a cool unnamed placeholder.

By convention, when we have a variable whose value we don’t want to use or care about, we often name it _. The problem is that with higher warning levels (-Wunused-variable), our compilation might fail because _ is unused.

In this case, even [[maybe_unused]] doesn’t help because _ is just a normal variable and is introduced twice. We can use std::ignore!

But even this solution won’t work all the time. We cannot use it with structured bindings, which are probably the most often used place where _ is used as variable names. And if you want to use _ with various structured bindings in the same (nested) scope, you have to look for other solutions.

The above piece of code will not compile, because we try to redefine _! In some cases, we can easily remove one of the ignored variables with the help of ranges!

Leave a Comment