EXPLORATION 49

image

Class Templates

A class can be a template , which makes all of its members templates. Every program in this book has used class templates, because much of the standard library relies on templates: the standard I/O streams, strings, vectors, and maps are all class templates. This Exploration takes a look at simple class templates.

Parameterizing a Type

Consider a simple point class, which stores an x and y coordinate. A graphics device driver might use int for the member types.

class point {public:   point(int x, int y) : x_{x}, y_{y} {}   int x() const { return x_; }   int y() const { return y_; }private:   int x_, y_;};

On the ...

Get Exploring C++ 11, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.