Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Class templates

Class templates are classes that use generic types, usually to declare its data members, but also to declare methods and local variables inside them:

template <typename T>class ArrayOf2 {    public:    T& operator[](size_t i) { return a_[i]; }    const T& operator[](size_t i) const { return a_[i]; }    T sum() const { return a_[0] + a_[1]; }    private:    T a_[2];};

This class is implemented once, and can then be used to define an array of two elements of any type:

ArrayOf2<int> i;i[0] = 1; i[1] = 5;std::cout << i.sum();     // 6ArrayOf2<double> x;x[0] = -3.5; x[1] = 4;std::cout << x.sum();     // 0.5ArrayOf2<char*> c;char s[] = "Hello";c[0] = s; c[1] = s + 2;

Pay particular attention to the last example—you might expect the ArrayOf2 template not ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content