Metaprogramming is Your Friend

Thomas Guest

Table of Contents

Editors and Editing
Metaprogramming in C++
Reflection and Introspection
Domain Specific Extensions
Concluding Thoughts


A Program to Write a Program

Whenever I create a new C++ file using Emacs a simple elisp script executes. This script:

  • places a standard header at the top of the file,
  • works out what year it is and adjusts the Copyright notice accordingly,
  • generates suitable #include guards (for header files),
  • inserts placeholders for Doxygen comments.

In short, the script automates some routine housekeeping for me.

On the face of it, nothing extraordinary is going on here. One program (the elisp script) helps me write another program (the C++ program which needs the new file). This unremarkable elisp script – a program to write a program – is, then, a metaprogram.

This article investigates some other metaprograms which, perhaps, we don't really notice, and some alternative metaprogramming techniques which, perhaps, we should be aware of.

What is Metaprogramming?

I like the definition found in the Wikipedia:

"Metaprogramming is the writing of programs that write or manipulate other programs (or themselves) as their data or that do part of the work that is otherwise done at runtime during compile time."

Actually, it's the first half of this definition I like (everything up to and including data). The second seems rather to weaken the concept by being too specific, and in my opinion its presence reflects the current interest in C++ template-metaprogramming – but a Wikipedia is bound to relect what's in fashion!

Why Metaprogram?

Having established what metaprogramming is the obvious follow-up is "Why?" Writing programs to manipulate ordinary data is challenging enough for most of us, so writing programs to manipulate programs must surely be either crazy or too clever by half.

Rather than attempt to provide a theoretical answer to "Why?" at this point, let's push the question on the stack and discuss some practical applications of metaprogramming.