r/cpp • • Jun 14 '21

match(it): A light-weight header-only pattern-matching library for C++17.

https://github.com/BowenFu/matchit.cpp
202 Upvotes

47 comments sorted by

View all comments

31

u/gracicot Jun 14 '21 edited Jun 14 '21

This is quite amazing what C++ can ship in a library, even though it's not perfect and uses macros.

12

u/[deleted] Jun 14 '21

Not arguing for them, but can someone explain the negative connotation around macros? I know the modern replacements are constexpr's and a lot of it has to do with lack of type definition, but is there more to it?

7

u/corysama Jun 14 '21

Macros can lead to bugs that are difficult to diagnose and difficult to fix. For example:

// ThirdPartyLib1.h
inline int min(int x, int y) { return x < y ? x : y; }
// 2000 more lines of complicated code using the min function.

// ThirdPartyLib2.h
// 2000 lines of complicated code.
int meiseIntegralizedNormalization(float deciprocand, float retrobasis);
#define min meiseIntegralizedNormalization
// 2000 more lines of complicated code using the min macro.

// MyLib.h
#include "ThirdPartyLib1.h"
#include "ThirdPartyLib2.h"
inline int factorize(int a, int b, int c) { return a / min(b, c); }

This will happily compile and run without warning about any conflicts or ambiguous overloads.