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 ...

Get ATL Internals: Working with ATL 8, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.