Generic programming techniques

Source: Internet
Author: User
Tags traits

Generic programming techniques
This is an incomplete survey of some of the generic programming techniques used in the boost libraries.
Table of contents
* Introduction
* The anatomy of a concept
* Traits
* Tag Dispatching
* Adaptors
* Type generators
* Object generators
* Policy classes
Introduction
Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations. in C ++, class and function templates are particularly ularly valid tive mechanisms for generic programming because they make the Generalization
Possible without sacrifle icing efficiency.
As a simple example of generic programming, we will look at how one might generalize the memcpy () function of the C standard library. An implementation of memcpy () might look like the following:
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 wowould 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
The destination, and compare pointers to know when to stop. the C ++ standard library groups requirements such as these into concepts, in this case the input iterator concept (for region2) and the output iterator concept (for region1 ).
If we rewrite the 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:
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 STD: list.
# 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 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 participates 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 C ++ standard library are already ented at the sgi stl site.
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 STD: iterator_traits <t> looks something like this:
Template <class iterator>
Struct iterator_traits {
Typedef... iterator_category;
Typedef... value_type;
Typedef... difference_type;
Typedef... pointer;
Typedef... reference;
};
The traits 'value_type gives generic code the type which the iterator is "pointing at", 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 participant type by (partially)
Specializing the traits template.
For an in-depth description of STD: iterator_traits, see this page provided by SGI. another very different expression of the traits idiom in the standard is 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 STD: Advance () function in the 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 the overloaded advance_dispatch () function. The appropriate advance_dispatch () is selected by the compiler based on whatever type the specified resolves to, either enabled, enabled, or disabled.
A tag is simply a class whose only purpose is to convey some property for use in tag dispatching and similar techniques. Refer to this page for a more detailed description of iterator tags.
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;
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 STD: reverse_iterator, which adapts an iterator type by reversing its motion upon increment/decrement, and
STD: Stack, which adapts a container to provide a simple stack interface.
A more comprehensive review of the adaptors in the standard can be found here.
Type generators
Note: The Type Generator concept has largely been superseded by the more refined notion of a metafunction. See C ++ template metaprogramming for an in-depth discussion of metafunctions.
A Type Generator is a template whose only purpose is to synthesize a new type or types based on its template argument (s) [1]. the generated type is usually expressed as a nested typedef named, appropriately type. A Type Generator is usually used to initialize lidate
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.
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:
Boost: filter_iterator_generator <my_predicate, my_base_iterator >:: type
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 STD: make_pair (const T &, const U &).
For example, given:
Struct widget {
Void tweak (INT );
};
STD: vector <widget *> widget_ptrs;
By chaining two standard Object generators, STD: bind2nd () and STD: mem_fun (), we can easily tweak all widgets:
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 abve wowould look like this:
Void tweak_all_widgets2 (INT Arg)
{
For_each (struct_ptrs.begin (), struct_ptrs.end (),
STD: binder2nd <STD: mem_funt T <void, widget, int> (
STD: mem_funt 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 STD: Allocator, which supplies Memory Management Behaviors to standard containers.
Policy classes have been inclued in detail by Andrei Alexandrescu in this chapter of his book, modern c ++ design. He writes:
In brief, policy-based class design fosters inserting ing a class with complex behavior out of each little classes (called indexes IES), 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 varous 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. this paper describes an old version of iterator_adaptor that used
Non-orthogonal policies. There is also precedent in the standard library: STD: char_traits, despite its name, acts as a sort ies class that determines the behaviors of STD: basic_string.
Notes
[1] type generators are sometimes viewed as a workaround for the lack of ''templated typedefs ''in C ++.

// Certificate //------------------------------------------------------------------------------------------------------------------------------------//

Ref:

Http://www.boost.org/community/generic_programming.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.