////
Copyright (c) 2024 The C++ Alliance, Inc. (https://cppalliance.org)

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

Official repository: https://github.com/boostorg/website-v2-docs
////
= Generic Programming Techniques
:navtitle: Generic Programming

_Generic programming_ is about generalizing software components so that they can be reused in a wide variety of situations. In pass:[C++], class and function templates are particularly effective mechanisms for generic programming because they make the generalization possible without sacrificing efficiency.

As a simple example of generic programming, we will look at how to generalize the `memcpy()` function of the C standard library. An implementation of `memcpy()` might look like the following:

```cpp
void* memcpy(void* region1, const void* region2, size_t n)
{
  const char* first = (const char*)region2;
  const char* last = ((const char*)region2) + n;
  char* result = (char*)region1;
  while (first != last)
    *result++ = *first++;
  return result;
}
```

The `memcpy()` function is already generalized to some extent by the use of `void*` so that the function can be used to copy arrays of different kinds of data. But what if the data we would like to copy is not in an array? Perhaps it is in a linked list. Can we generalize the notion of copy to any sequence of elements? Looking at the body of `memcpy()`, the function's _minimal requirements_ are that it needs to traverse through the sequence using some sort of pointer, access elements pointed to, write the elements to the destination, and compare pointers to know when to stop. The pass:[C++] standard library groups requirements such as these into _concepts_, in this case the https://en.cppreference.com/w/cpp/named_req/InputIterator[Input Iterator] concept (for region2) and the https://en.cppreference.com/w/cpp/named_req/OutputIterator[Output Iterator] concept (for region1).

If we rewrite `memcpy()` as a function template, and use the Input Iterator and Output Iterator concepts to describe the requirements on the template parameters, we can implement a highly reusable `copy()` function in the following way:

```cpp
template <typename InputIterator, typename OutputIterator>
OutputIterator
copy(InputIterator first, InputIterator last, OutputIterator result)
{
  while (first != last)
    *result++ = *first++;
  return result;
}
```

Using the generic `copy()` function, we can now copy elements from any kind of sequence, including a linked list that exports iterators such as https://en.cppreference.com/w/cpp/container/list[std::list].

```cpp
#include <list>
#include <vector>
#include <iostream>

int main()
{
  const int N = 3;
  std::vector<int> region1(N);
  std::list<int> region2;

  region2.push_back(1);
  region2.push_back(0);
  region2.push_back(3);
  
  std::copy(region2.begin(), region2.end(), region1.begin());

  for (int i = 0; i < N; ++i)
    std::cout << region1[i] << " ";
  std::cout << std::endl;
}
```

== Anatomy of a Concept

A _concept_ is a set of requirements consisting of valid expressions, associated types, invariants, and complexity guarantees. A type that satisfies the requirements is said to _model_ the concept. A concept can extend the requirements of another concept, which is called _refinement_.

* _Valid Expressions_ are pass:[C++] expressions which must compile successfully for the objects involved in the expression to be considered models of the concept.
* _Associated Types_ are types that are related to the modeling type in that they participate in one or more of the valid expressions. Typically associated types can be accessed either through `typedefs` nested within a class definition for the modeling type, or they are accessed through a <<Traits>> class.
* _Invariants_ are run-time characteristics of the objects that must always be true, that is, the functions involving the objects must preserve these characteristics. The invariants often take the form of _pre-conditions_ and _post-conditions_.
* _Complexity Guarantees_ are maximum limits on how long the execution of one of the valid expressions will take, or how much of various resources its computation will use.

The concepts used in the pass:[C++] Standard Library are documented in the https://en.cppreference.com/w/cpp/concepts[C++ reference Concepts library].

== Traits

A traits class provides a way of associating information with a compile-time entity (a type, integral constant, or address). For example, the class template https://en.cppreference.com/w/cpp/iterator/iterator_traits[std::iterator_traits<T>] looks something like this:

```cpp
template <class Iterator>
struct iterator_traits {
  typedef ... iterator_category;
  typedef ... value_type;
  typedef ... difference_type;
  typedef ... pointer;
  typedef ... reference;
};
```

The `value_type` of the traits specifies the type of data that the iterator points to, in generic code, while the `iterator_category` can be used to select more efficient algorithms depending on the iterator's capabilities.

A key feature of traits templates is that they're non-intrusive: they allow us to associate information with arbitrary types, including built-in types and types defined in third-party libraries, Normally, traits are specified for a particular type by (partially) specializing the traits template.

For more details, refer to https://en.cppreference.com/w/cpp/iterator/iterator_traits[std::iterator_traits]. Another very different expression of the traits idiom in the standard is https://en.cppreference.com/w/cpp/types/numeric_limits[std::numeric_limits<T>] which provides constants describing the range and capabilities of numeric types.

== Tag Dispatching

_Tag dispatching_ is a way of using function overloading to dispatch based on properties of a type, and is often used hand in hand with traits classes. A good example of this synergy is the implementation of the https://en.cppreference.com/w/cpp/iterator/advance[std::advance] function in the pass:[C++] Standard Library, which increments an iterator n times. Depending on the kind of iterator, there are different optimizations that can be applied in the implementation. If the iterator is random access (can jump forward and backward arbitrary distances), then the `advance()` function can simply be implemented with `i += n`, and is very efficient: constant time. Other iterators must be advanced in steps, making the operation linear in n. If the iterator is bidirectional, then it makes sense for n to be negative, so we must decide whether to increment or decrement the iterator.

The relation between tag dispatching and traits classes is that the property used for dispatching (in this case the `iterator_category`) is often accessed through a traits class. The main `advance()` function uses the `iterator_traits` class to get the `iterator_category`. It then makes a call to the overloaded `advance_dispatch()` function. The appropriate `advance_dispatch()` is selected by the compiler, based on whatever type the `iterator_category` resolves to, either `input_iterator_tag`, `bidirectional_iterator_tag`, or `random_access_iterator_tag`. A tag is simply a class whose only purpose is to convey some property for use in tag dispatching and similar techniques. Refer to https://en.cppreference.com/w/cpp/iterator/iterator_tags[cppreference: iterator_tags] for more information.

```cpp
namespace std {
  struct input_iterator_tag { };
  struct bidirectional_iterator_tag { };
  struct random_access_iterator_tag { };

  namespace detail {
    template <class InputIterator, class Distance>
    void advance_dispatch(InputIterator& i, Distance n, input_iterator_tag) {
      while (n--) ++i;
    }

    template <class BidirectionalIterator, class Distance>
    void advance_dispatch(BidirectionalIterator& i, Distance n, 
       bidirectional_iterator_tag) {
      if (n >= 0)
        while (n--) ++i;
      else
        while (n++) --i;
    }

    template <class RandomAccessIterator, class Distance>
    void advance_dispatch(RandomAccessIterator& i, Distance n, 
       random_access_iterator_tag) {
      i += n;
    }
  }

  template <class InputIterator, class Distance>
  void advance(InputIterator& i, Distance n) {
    typename iterator_traits<InputIterator>::iterator_category category;
    detail::advance_dispatch(i, n, category);
  }
}
```

== Adaptors

An _adaptor_ is a class template which builds on another type or types to provide a new interface or behavioral variant. Examples of standard adaptors are https://en.cppreference.com/w/cpp/iterator/reverse_iterator[std::reverse_iterator], which adapts an iterator type by reversing its motion upon increment/decrement, and https://en.cppreference.com/w/cpp/container/stack[std::stack], which adapts a container to provide a simple stack interface.

A comprehensive review of the adaptors in the standard can be found in https://dl.acm.org/doi/10.1145/249118.249120[An overview of the standard template library].

== Type Generators

Note:: The _type generator_ concept has largely been superseded by the more refined notion of a _metafunction_. Refer to xref:faq.adoc#templates[Templates] and the documentation for boost:mp11[].

A type generator is a template whose only purpose is to synthesize a new type or types based on its template arguments. The generated type is usually expressed as a nested `typedef` named, appropriately `type`. A type generator is usually used to consolidate a complicated type expression into a simple one.

This example uses an old version of `iterator_adaptor` whose design didn't allow derived iterator types. As a result, every adapted iterator had to be a specialization of `iterator_adaptor` itself and generators were a convenient way to produce those types.

```cpp
template <class Predicate, class Iterator, 
    class Value = complicated default,
    class Reference = complicated default,
    class Pointer = complicated default,
    class Category = complicated default,
    class Distance = complicated default
         >
struct filter_iterator_generator {
    typedef iterator_adaptor<
        
        Iterator,filter_iterator_policies<Predicate,Iterator>,
        Value,Reference,Pointer,Category,Distance> type;
};
```

Now, that's complicated, but producing an adapted filter iterator using the generator is much easier. You can usually just write:

```cpp
boost::filter_iterator_generator<my_predicate,my_base_iterator>::type
```

Note:: Type generators are sometimes viewed as a workaround for the lack of “templated typedefs” in pass:[C++].

== Object Generators

An _object generator_ is a function template whose only purpose is to construct a new object out of its arguments. Think of it as a kind of generic constructor. An object generator may be more useful than a plain constructor when the exact type to be generated is difficult or impossible to express and the result of the generator can be passed directly to a function rather than stored in a variable. Most Boost object generators are named with the prefix `make_`, after https://en.cppreference.com/w/cpp/utility/pair/make_pair[std::make_pair(const T&, const U&)].

For example, given:

```cpp
struct widget {
  void tweak(int);
};
std::vector<widget *> widget_ptrs;
```

By chaining two standard object generators, https://en.cppreference.com/w/cpp/utility/functional/bind12[std::bind2nd] and https://en.cppreference.com/w/cpp/utility/functional/mem_fun[std::mem_fun], we can easily tweak all widgets:

```cpp
void tweak_all_widgets1(int arg)
{
   for_each(widget_ptrs.begin(), widget_ptrs.end(),
      bind2nd(std::mem_fun(&widget::tweak), arg));
}
```

Without using object generators the example above would look like this:

```cpp
void tweak_all_widgets2(int arg)
{
   for_each(struct_ptrs.begin(), struct_ptrs.end(),
      std::binder2nd<std::mem_fun1_t<void, widget, int> >(
          std::mem_fun1_t<void, widget, int>(&widget::tweak), arg));
}
```

As expressions get more complicated the need to reduce the verbosity of type specification gets more compelling.

== Policy Classes

A _policy class_ is a template parameter used to transmit behavior. An example from the standard library is https://en.cppreference.com/w/cpp/memory/allocator[std::allocator], which supplies memory management behaviors to standard containers.

Policy classes have been explored in detail by Andrei Alexandrescu in one chapter of his book, _Modern pass:[C++] Design_. He writes:

_"In brief, policy-based class design fosters assembling a class with complex behavior out of many little classes (called policies), each of which takes care of only one behavioral or structural aspect. As the name suggests, a policy establishes an interface pertaining to a specific issue. You can implement policies in various ways as long as you respect the policy interface._

_Because you can mix and match policies, you can achieve a combinatorial set of behaviors by using a small core of elementary components."_

Andrei's description of policy classes suggests that their power is derived from granularity and orthogonality. Less-granular policy interfaces have been shown to work well in practice, though. There is also precedent in the standard library: https://en.cppreference.com/w/cpp/string/char_traits[std::char_traits], despite its name, acts as a policies class that determines the behaviors of https://en.cppreference.com/w/cpp/string/basic_string[std::basic_string].

== Acknowledgements

This topic was originally written by David Abrahams, in 2001.

== See Also

* boost:any[] : provides a type-safe container for storing values of any type and retrieved dynamically at runtime.
* boost:variant[] : provides a type-safe container for representing a fixed set of alternative types, and accessed using type-safe visitor patterns.
* boost:iterator[] : provides utilities for working with iterators and iterator ranges and includes iterator adaptors, iterator categories, and iterator concepts.
* boost:fusion[] : provides a set of data structures and algorithms for working with heterogeneous sequences of elements in a generic and type-safe manner. 
* boost:mp11[] : provides a modern metaprogramming framework.
* boost:type-traits[] : provides support for fundamental properties of types.
* xref:faq.adoc[]
