Skip to content

Commit 0ed11bf

Browse files
authored
Migrate Generic Programming topic to User Guide (#225)
1 parent 7ecd7e2 commit 0ed11bf

File tree

2 files changed

+241
-0
lines changed

2 files changed

+241
-0
lines changed

user-guide/modules/ROOT/nav.adoc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Official repository: https://github.com/boostorg/website-v2-docs
2929
** xref:task-parallel-computation.adoc[]
3030
3131
* Development
32+
** xref:generic-programming.adoc[]
3233
** xref:exception-safety.adoc[]
3334
3435
* Community
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
////
2+
Copyright (c) 2024 The C++ Alliance, Inc. (https://cppalliance.org)
3+
4+
Distributed under the Boost Software License, Version 1.0. (See accompanying
5+
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6+
7+
Official repository: https://github.com/boostorg/website-v2-docs
8+
////
9+
= Generic Programming Techniques
10+
:navtitle: Generic Programming
11+
12+
_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.
13+
14+
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:
15+
16+
```cpp
17+
void* memcpy(void* region1, const void* region2, size_t n)
18+
{
19+
const char* first = (const char*)region2;
20+
const char* last = ((const char*)region2) + n;
21+
char* result = (char*)region1;
22+
while (first != last)
23+
*result++ = *first++;
24+
return result;
25+
}
26+
```
27+
28+
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).
29+
30+
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:
31+
32+
```cpp
33+
template <typename InputIterator, typename OutputIterator>
34+
OutputIterator
35+
copy(InputIterator first, InputIterator last, OutputIterator result)
36+
{
37+
while (first != last)
38+
*result++ = *first++;
39+
return result;
40+
}
41+
```
42+
43+
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].
44+
45+
```cpp
46+
#include <list>
47+
#include <vector>
48+
#include <iostream>
49+
50+
int main()
51+
{
52+
const int N = 3;
53+
std::vector<int> region1(N);
54+
std::list<int> region2;
55+
56+
region2.push_back(1);
57+
region2.push_back(0);
58+
region2.push_back(3);
59+
60+
std::copy(region2.begin(), region2.end(), region1.begin());
61+
62+
for (int i = 0; i < N; ++i)
63+
std::cout << region1[i] << " ";
64+
std::cout << std::endl;
65+
}
66+
```
67+
68+
== Anatomy of a Concept
69+
70+
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_.
71+
72+
* _Valid Expressions_ are pass:[C++] expressions which must compile successfully for the objects involved in the expression to be considered models of the concept.
73+
* _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.
74+
* _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_.
75+
* _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.
76+
77+
The concepts used in the pass:[C++] Standard Library are documented in the https://en.cppreference.com/w/cpp/concepts[C++ reference Concepts library].
78+
79+
== Traits
80+
81+
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:
82+
83+
```cpp
84+
template <class Iterator>
85+
struct iterator_traits {
86+
typedef ... iterator_category;
87+
typedef ... value_type;
88+
typedef ... difference_type;
89+
typedef ... pointer;
90+
typedef ... reference;
91+
};
92+
```
93+
94+
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.
95+
96+
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.
97+
98+
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.
99+
100+
== Tag Dispatching
101+
102+
_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.
103+
104+
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.
105+
106+
```cpp
107+
namespace std {
108+
struct input_iterator_tag { };
109+
struct bidirectional_iterator_tag { };
110+
struct random_access_iterator_tag { };
111+
112+
namespace detail {
113+
template <class InputIterator, class Distance>
114+
void advance_dispatch(InputIterator& i, Distance n, input_iterator_tag) {
115+
while (n--) ++i;
116+
}
117+
118+
template <class BidirectionalIterator, class Distance>
119+
void advance_dispatch(BidirectionalIterator& i, Distance n,
120+
bidirectional_iterator_tag) {
121+
if (n >= 0)
122+
while (n--) ++i;
123+
else
124+
while (n++) --i;
125+
}
126+
127+
template <class RandomAccessIterator, class Distance>
128+
void advance_dispatch(RandomAccessIterator& i, Distance n,
129+
random_access_iterator_tag) {
130+
i += n;
131+
}
132+
}
133+
134+
template <class InputIterator, class Distance>
135+
void advance(InputIterator& i, Distance n) {
136+
typename iterator_traits<InputIterator>::iterator_category category;
137+
detail::advance_dispatch(i, n, category);
138+
}
139+
}
140+
```
141+
142+
== Adaptors
143+
144+
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.
145+
146+
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].
147+
148+
== Type Generators
149+
150+
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[].
151+
152+
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.
153+
154+
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.
155+
156+
```cpp
157+
template <class Predicate, class Iterator,
158+
class Value = complicated default,
159+
class Reference = complicated default,
160+
class Pointer = complicated default,
161+
class Category = complicated default,
162+
class Distance = complicated default
163+
>
164+
struct filter_iterator_generator {
165+
typedef iterator_adaptor<
166+
167+
Iterator,filter_iterator_policies<Predicate,Iterator>,
168+
Value,Reference,Pointer,Category,Distance> type;
169+
};
170+
```
171+
172+
Now, that's complicated, but producing an adapted filter iterator using the generator is much easier. You can usually just write:
173+
174+
```cpp
175+
boost::filter_iterator_generator<my_predicate,my_base_iterator>::type
176+
```
177+
178+
Note:: Type generators are sometimes viewed as a workaround for the lack of “templated typedefs” in pass:[C++].
179+
180+
== Object Generators
181+
182+
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&)].
183+
184+
For example, given:
185+
186+
```cpp
187+
struct widget {
188+
void tweak(int);
189+
};
190+
std::vector<widget *> widget_ptrs;
191+
```
192+
193+
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:
194+
195+
```cpp
196+
void tweak_all_widgets1(int arg)
197+
{
198+
for_each(widget_ptrs.begin(), widget_ptrs.end(),
199+
bind2nd(std::mem_fun(&widget::tweak), arg));
200+
}
201+
```
202+
203+
Without using object generators the example above would look like this:
204+
205+
```cpp
206+
void tweak_all_widgets2(int arg)
207+
{
208+
for_each(struct_ptrs.begin(), struct_ptrs.end(),
209+
std::binder2nd<std::mem_fun1_t<void, widget, int> >(
210+
std::mem_fun1_t<void, widget, int>(&widget::tweak), arg));
211+
}
212+
```
213+
214+
As expressions get more complicated the need to reduce the verbosity of type specification gets more compelling.
215+
216+
== Policy Classes
217+
218+
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.
219+
220+
Policy classes have been explored in detail by Andrei Alexandrescu in one chapter of his book, _Modern pass:[C++] Design_. He writes:
221+
222+
_"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._
223+
224+
_Because you can mix and match policies, you can achieve a combinatorial set of behaviors by using a small core of elementary components."_
225+
226+
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].
227+
228+
== Acknowledgements
229+
230+
This topic was originally written by David Abrahams, in 2001.
231+
232+
== See Also
233+
234+
* boost:any[] : provides a type-safe container for storing values of any type and retrieved dynamically at runtime.
235+
* boost:variant[] : provides a type-safe container for representing a fixed set of alternative types, and accessed using type-safe visitor patterns.
236+
* boost:iterator[] : provides utilities for working with iterators and iterator ranges and includes iterator adaptors, iterator categories, and iterator concepts.
237+
* boost:fusion[] : provides a set of data structures and algorithms for working with heterogeneous sequences of elements in a generic and type-safe manner.
238+
* boost:mp11[] : provides a modern metaprogramming framework.
239+
* boost:type-traits[] : provides support for fundamental properties of types.
240+
* xref:faq.adoc[]

0 commit comments

Comments
 (0)