O'Reilly logo

ATL Internals: Working with ATL 8, Second Edition by Chris Sells, Brent Rector, Kirk Fertitta, Christopher Tavares

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix A. C++ Templates by Example

This chapter is meant to be a brief introduction to the basics of C++ templates using examples. It also shows some of the advanced template features that ATL uses, but without any ATL code cluttering up things. For a more thorough introduction to templates, see Stan Lippman’s C++ Primer (Addison-Wesley, 2005).

The Need for Templates

Imagine a simple bounds-checked array class:

#define MAX_ELEMS 8class Array {public:  long& operator[](size_t n) {    if( n < 0 || n >= MAX_ELEMS ) throw "out of bounds!";    return m_rg[n];  }protected:  long m_rg[MAX_ELEMS];};

This class makes quiet, hard-to-find errors loud and easy to find:

void main(int argc, char* argv[]) {  long rg[8]; // Built in array type  rg[8] = 1;  // will corrupt the stack, but quietly ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required