C++ templates for Fun and Profit

Wijaa asks on stackoverflow: What’s the most brilliant use of templates you’ve ever encountered?

Reading the linked articles gave me much joy. Here are some highlights:

  • In FOREACH Redux, Eric Niebler describes his long path to the BOOST_FOREACH macro, which emulates C#’s foreach statement in C++. At the core, it all revolves around using the conditional operator ?: with templates to work the compilers type inference engine:
    
    struct rvalue_probe
    {
       template< class R > operator R ()
       {
            throw "rvalue";
       }
       template< class L > operator L &amp; () const
       {
            throw "lvalue";
       }
    };
    
    #define RVALUE_TEST(container) \
       try { ( true ? rvalue_probe() : (container) ); } \
       catch( char const * result ) { cout <<result << '\n'; }
    

    This snippet for example uses the overload resolution rules to decide whether container is an rvalue or an lvalue, without evaluating it. For a detailed explanation, read the full article.

  • The next link leads to the Spirit parser generator’s quick start. Except that Spirit is no parser generator like yacc. All rules are directly defined in C++. This one-liner calls f every time a real number is recognized. Multiple numbers are separated with comma.

    real_p[&f] >> *(',' >> real_p[&f])

    real_p is a parser for real numbers, >> puts parsers into sequences and * is the Kleene Star. Read the quick start for an explanation how this all fits together.

So whatever you do, don’t say C++ didn’t make any progress.

Have fun and a nice Sunday!

Leave a Reply