CHAPTER 5

image

Interfaces

Templates are used as interfaces in two different ways: to provide sets of atomic functions and to obtain compile-time polymorphism.

If several functions use the same portion of the interface of an object, you can factor them out in a single template:

void do_something(std::vector<double>& v){   if (v.empty())      // ...   ... v.size();   for_each(v.begin(), v.end(), my_functor());   ...}void do_something(std::list<double>& L){   if (L.empty())      // ...   ... L.size();   for_each(L.begin(), L.end(), my_functor());   ...}

becomes:

template <typename T>void do_something(T& L){   if (L.empty())      // ...   ... L.size(); ...

Get Advanced Metaprogramming in Classic C++ 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.