C++ ORM DSL via Macros

Macros, like the goto statement, have become somewhat frowned upon nowadays, but (IMO) I think that’s a little excessive. Macros, used judiciously, can be beneficial.

For example, you may want code to execute in debug but not release, you can define the symbol accordingly and avoid hundreds of #ifdef’s throughout your codebase. Arguably, you could achieve the same effect in other ways, but not as simply.

Recently, I was going through some of my old code and found a (pre-modern C++) client  ORM  I had written which leveraged macros as a DSL. You essentially use the macros to declare your entities, classes and queries in a header file and the compiler generates the appropriate code. It’s pretty basic, and doesn’t support aggregation, but was sufficient for our needs at the time.

Here is an example .h file declaration:

useraccounth

That’s it, you just declare it and use it like so:

useraccountc

The table comes with basic CRUD functions, but here’s an example of extending it via macros:

dudesh

And an example using the generated functions:

dudesc

Now for the macro magic which generates the code behind the scenes:
(note this is all on one line, formatted here for readability)

selectby1

The function the above macro depends upon to do it’s work:

selectwhere

In general, the advice to avoid macros is wise, there are known pitfalls. But in specific cases they can be put to good use when applied carefully and sparingly.

In my opinion, macros aren’t completely bad 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s