r/cpp • • 5d ago

Pattern Matching for C++29

https://mpark.github.io/programming/2026/11/30/pattern-matching-for-cpp29/
251 Upvotes

105 comments sorted by

View all comments

8

u/fortsnek274 5d ago

And one of the irritants is that when I do something like that:

if (const auto *FD = dyn_cast<FunctionDecl>(D))
  use(FD);
else if (const auto *VD = dyn_cast<VarDecl>(D))
  use(VD);

The variables have to have a different name as they stay in scope.

6

u/Lahvuun 5d ago edited 5d ago

Of course this has long been solved by C++17's if statement with initializer:

if (const auto *FOO = dyn_cast<FunctionDecl>(D); FOO)
  use(FOO);
else if (const auto *FOO = dyn_cast<VarDecl>(D); FOO)
  use(FOO);

edit: that is wrong, need to instead use separate if statements:

if (const auto *FOO = dyn_cast<FunctionDecl>(D); FOO)
  use(FOO);
if (const auto *FOO = dyn_cast<VarDecl>(D); FOO)
  use(FOO);

2

u/fortsnek274 5d ago

That's the same code. MSVC warns about variable shadowing.

2

u/SirClueless 5d ago

Pretty sure this is the exact same, and will fail if using -Wshadow -Werror: https://godbolt.org/z/Tjj4Y9Gd4

3

u/Lahvuun 5d ago

Yes, I forgot the variable is still visible in the else block. Need to use two separate ifs.

1

u/mapronV 23h ago

yeah, that gives 2 casts that kills the purpose, unfortunately.

0

u/msew 4d ago
  • in wrong spot

2

u/crowbarous 4d ago

The variables are in nested scopes, so they will shadow one another successfully. Your code as presented is OK if both variables were called, say, DD. A more unfortunate problem is that neither can be called D.

0

u/msew 4d ago
  • in wrong spot