May 2015
Intermediate to advanced
572 pages
9h 52m
English
CHAPTER 5
![]()
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(); ...