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 O’Reilly online learning.

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