Templates

Date Arrow  March 13, 2008

Did you knew this is possible in C++? I didn’t.

This feature is called “local classes” and is part of the standard; the limitations are that these local classes cannot have static member variables and cannot access nonstatic local variables. But, as Alexandrescu points out (page 28), you can use them in template functions:

Not only that, but partial template specialization and template-based compile-time verifications just blew me away. The second chapter of the book was realizing I just haven’t had the slightest clue about all the cool things you could do with C++!

Tagged   Code · Opinion

5 Comments

  • #1.   patrick 03.14.2008

    I can even pass child classes as a template parameter of a class. The big classic is the singleton:

    template <class C>
    class Singleton {
    private:
    static C instance;
    public:

    }

    class Toto: public Singleton<Toto> {…}

    How cool is that?

  • #2.   adrian 03.14.2008

    Frankly I’m amazed. It’s a completely new language. This book is enlightening!

  • #3.   Robert 'Groby' Blum 05.12.2008

    Beware - you pay a price for that power. Namely, insanely long compile times once you start relying on these features.

    To be fair, that’s probably mostly attributable to the fact that C++ really wants to be backwards compatible to 1970’s style C - include file madness, undecidable parsing, lots of fun….

  • #4.   Adrian 05.13.2008

    Hi Robert, thanks for your comments! Indeed I have witnessed (and suffered) those longer compile times, but what I find fascinating is the kind of constructions that you can build with templates. In terms of expresiveness, I think it’s huge.

  • #5.   Robert 'Groby' Blum 05.15.2008

    It is indeed - template expressions are turing complete, so you can really do whatever you want at compile time. I think somebody somewhere wrote a “Towers of Hanoi” solver in template expressions…

    It just seems to me it’s one of the slower turing machines around ;)

Commenting