I recently wrote a program that I found useful enough to share. The original idea was due to COG (http://www.nedbatchelder.com/code/cog/index.html), which is a Python program with similar functionality.
Do you ever find yourself writing code like the following?
class A { private: int a_; public: // ... bool operator<(int b) const { return this->a_ < b; } bool operator<=(int b) const { return this->a_ <= b; } bool operator==(int b) const { return this->a_ == b; } bool operator!=(int b) const { return this->a_ != b; } bool operator>=(int b) const { return this->a_ >= b; } bool operator>(int b) const { return this->a_ > b; } };
Notice how all these overloaded operators are essentially the same format? You could use a hairy C macro to do this sort of job. Or, you could use PCG.
Using PCG, the above code looks more like this:
class A { private: int a_; public: // ... /* <<<pcg foreach('<', '<=', '==', '!=', '>=', '>') { print <<"EOF"; bool operator${_}(int b) const { return this->a_ ${_} b; } EOF }>>> */ /* <<</pcg>>> */ };
Hitting [F6] in Emacs, your buffer magically fills with correct, typo-free code!
Another tip: set up scaffolding in PCG, generate code, and then edit your <<<pcg ...>>> tag to instead read <<<!pcg ...>>>. Subsequent runs of PCG will not overwrite your edits.
Yet another tip: keep anything but one-liners in a module in the same directory as your source, or if it's reuseable, in the same directory as PCG. Use the module at the beginning of your source. Watch this module (test_pcg.pm) turn this:
// <<<pcg use test_pcg;>>> // <<</pcg>>> /* <<<pcg test_pcg::bean_chainable(0, 'Test', 'test1' => 'byte', 'test2' => 'double', 'test3' => 'long', 'crap4' => 'String');>>> */ // <<</pcg>>>
...into a JavaBean for you (test.java)!
PCG is not the right tool for every job. But, sometimes you don't have much choice (for instance, if you are building objects based on a database schema, or writing tricky parser code), and for those tasks, PCG can be a real timesaver.
Why did I write this instead of just using COG? Well, Perl is more readily available on my home machines, lends itself well to this type of processing (offering many types of quoting), and I like this single-script solution.