Preprocessor Lists

At work, I found myself needing to do a repetitive operation at compile time on a set of symbols. We all know what to do in that situation:

    #define OPERATION(x) ... some big long thing in terms of x ...
    OPERATION(symbol1)
    OPERATION(symbol2)
    OPERATION(symbol3)
    ...

I’m doing two such operations in different places on the same set of symbols. And I’m about to add a third. My refactor alarm goes off: I need to abstract this.

How do you iterate over a list of symbols at compile time? Let’s take a technique from lambda calculus: the we define the list as a function which iterates over itself:

    #define SYMLIST(f) \
        f(symbol1) \
        f(symbol2) \
        f(symbol3)

Then to do three different operations on these symbols, I can simply define the operations and use the list like so:

    #define OPERATION1(x) ... something involving x ...
    #define OPERATION2(x) ... something else involving x ...
    #define OPERATION3(x) ... you get the picture ...
    SYMLIST(OPERATION1)
    SYMLIST(OPERATION2)
    SYMLIST(OPERATION3)

Abstraction: Satisfied.

About these ads

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s