Practice and Opening Boost Type Erasure

I am reading about boost type erasure and I am trying to figure out potential uses. I would like to practice this a bit while reading tons of documentation on this topic (it looks great). The most quoted area of ​​the application that integrates / exchanges data between the client and server. Can you offer any other example or exercise where I can play, I beat this library?

+6
source share
1 answer

The Erasure type is useful in an unusual number of situations, to such an extent that it can be considered as a fundamentally absent function of the language that combines common and object-oriented programming styles.

When we define a class in C ++, what we really define is a very specific type and a very specific interface , and that these two things do not have to be connected. A type deals with data, where when an interface deals with transformations of that data. Generic code, for example, in STL, does not care about type , it cares about interface : you can sort any container or container sequence using std::sort if it provides a comparison and an interface iterator.

Unfortunately, common C ++ code requires compile-time polymorphism: templates . This does not help in things that cannot be known until runtime, or in things that require a uniform interface.

A simple example: how do you store several different types in one container? The simplest mechanism is to store all types in void *, possibly with some type information, to distinguish them. Another way is to recognize that all of these types have the same interface : search. If we could create a single interface for retrieval , then specialize it for each type, then it will be as if the part of type were erased.

any_iterator is another very useful reason: if you need to any_iterator over several different containers with the same interface, you need to remove type from the container from the type iterator. boost :: any_range is a subtle improvement on this, extending it from iterators to ranges, but the basic idea is the same.

In short, at any time when you need to switch from several types with a similar interface to one type using one interface , you will need to erase a type of a specific type. This is a run-time method that compares compile-time patterns.

+17
source

Source: https://habr.com/ru/post/951868/


All Articles