Item 60. Generic Algorithms

A generic algorithm is a function template that is designed in such a way that it can be easily and effectively customized at compile time according to the context of its use. Let’s look at a function template that doesn’t meet these exacting standards and is therefore not a proper generic algorithm:

image

This template can be used to sort an array of objects, provided that the objects can be compared with a < operator and copied. For example, we can sort an array of our String objects from Assignment and Initialization Are Different [12, 41]:

String names[] = { "my", "dog", "has", "fleece" };const int namesLen = sizeof(names)/sizeof(names[0]); ...

Get C++ Common Knowledge: Essential Intermediate Programming 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.