Библиотека карт свойств Boost состоит в основном из спецификаций интерфейса в виде концепций (аналогично концепциям итератора в STL [2]). Эти спецификации интерфейса предназначены для использования разработчиками общих библиотек при передаче пользователям требований по параметрам шаблонов. В частности, концепции Boost Property Map определяют интерфейс общего назначения для отображения ключевых объектов на соответствующие объекты значений, тем самым скрывая детали того, как отображение реализуется из алгоритмов. Реализация типов, выполняющих интерфейс карты свойств, зависит от клиента алгоритма. Требования к картам свойств намеренно расплывчаты по типу ключевых и ценных объектов, чтобы обеспечить максимальную универсальность в шаблонах функций общей библиотеки.
Потребность в интерфейсе карты свойств возникла из библиотеки Boost Graph Library (BGL), которая содержит множество примеров алгоритмов, использующих концепции карты свойств для указания своего интерфейса. Например, обратите внимание на параметр шаблона ColorMapbreadth_first_search. Кроме того, BGL содержит множество примеров конкретных типов, реализующих интерфейс карты свойств. Класс adjacency_list реализует карты свойств для доступа к объектам (свойствам), которые прикреплены к вершинам и краям графа.
Библиотека Boost Property Map Library также содержит несколько адаптеров, которые преобразуют обычно используемые структуры данных, которые реализуют операцию отображения, такую как встроенные массивы (указатели), итераторы и std::map, чтобы иметь интерфейс карты свойств. Эти адаптеры предназначены не для удовлетворения всех потребностей в отображении, а служат примером того, как реализовать интерфейс, а также охватывают несколько распространенных случаев. Смотрите файлы заголовка для деталей.
Карты свойств представляют собой статически типизированные объекты. Если вам нужно получить доступ к картам свойств в более динамической настройке (например, потому что вы читаете неизвестный набор атрибутов из файла), вы можете использовать класс dynamic_properties для доступа к набору карт свойств через динамически типизированный интерфейс.
Property Map Concepts
The property map interface consists of a set of concepts (see
definition of "concept" in [1] and [2]) that
define a syntax for mapping key objects to corresponding value
objects. Since the property map operations are global functions
(actually they don't have to be global, but they are always called
unqualified and may be found via argument dependent lookup), it is
possible to overload the map functions such that nearly arbitrary
property map types and key types can be used. The interface for
property maps consists of three functions: get(),
put(), and operator[]. The following concrete
example from example1.cpp shows how the
three functions could be used to access the addresses associated with
various people. We use a separate function template here to highlight
the parts of the program that use the property map concept
interface. In the main() function we use std::map
and boost::associative_property_map, but it would have been
OK to use any type (including a custom type that you create) that
fulfills the property map requirements.
For each property map object there is a set of valid keys
for which the mapping to value objects is defined. Invoking a
property map function on an invalid key results in
undefined behavior. The property map concepts do not specify how
this set of valid keys is created or modified. A function that uses a
property map must specify the expected set of valid keys in its
preconditions.
The need for property maps came out of the design of the Boost
Graph Library, whose algorithms needed an interface for accessing
properties attached to vertices and edges in a graph. In this context
the vertex and edge descriptors are the key type of the property
maps.
Several categories of property maps provide
different access capabilities:
readable
The associated property data can only be read.
The data is returned by-value. Many property maps defining the
problem input (such as edge weight) can be defined as readable
property maps.
writeable
The associated property can only be written to.
The parent array used to record the paths in a bread-first search tree
is an example of a property map that would be defined writeable.
read/write
The associated property can both be written and read.
The distance property use in Dijkstra's shortest paths algorithm
would need to provide both read and write capabilities.
lvalue
The associated property is actually represented in
memory and it is possible to get a reference to it.
The property maps in the lvalue
category also support the requirements for read/write property
maps.
There is a separate concept defined for each of the four property
map categories. These property map concepts are listed
below, with links to the documentation for each of them.
Similar to the std::iterator_traits class of the STL, there
is a boost::property_traits class that can be used to deduce
the types associated with a property map type: the key and value
types, and the property map category. There is a specialization
of boost::property_traits so that pointers can be used as
property map objects. In addition, the property map
functions are overloaded for pointers. These traits classes and
functions are defined in <boost/property_map/property_map.hpp>.
Встроенные типы указателей C++. Следующая специализациясвойств_ черткласса и перегрузкипоставить()иполучить()позволяет использовать встроенные типы указателей C++ в качестве карт свойств. Они определены вboost/property_map/property_map.hpp. Более конкретно, это означает, чтоT*является модельюLvaluePropertyMap, учитывая ключевой тип, который является по меньшей мере конвертируемымstd::ptrdiff_t.
namespace boost {
// specialization for using pointers as property maps
template <typename T>
struct property_traits<T*> {
typedef T value_type;
typedef T& reference;
typedef std::ptrdiff_t key_type;
typedef random_access_iterator_pa_tag category;
};
// overloads of the property map functions for pointers
template<>
void put(T* pmap, std::ptrdiff_t k, const T& val) { pmap[k] = val; }
template<>
const T& get(const T* pmap, std::ptrdiff_t k) { return pmap[k]; }
}
The property map interface originated as data accessors in
Dietmar Kühl's Masters Thesis on generic graph algorithms. The
property map idea also appeared under the guise of decorators
in early versions of the Generic Graph Component Library (GGCL), which
is now the Boost Graph Library (BGL). The main motivation for the
property map interface was to support the access of data associated
with vertices and edges in a graph, though the applicability of
property maps goes beyond this.
Acknowledgments
Thanks go to Dietmar Kühl for coming up with this mechanism, and
thanks go to the Boost members who helped refine and improve the
property map interface. Thanks to Dave Abrahams for managing the
formal review of the BGL which included the property map library.
Notes to Implementors
Copying a property map should be inexpensive since they are often
passed by value.
Статья Property Map Library раздела может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.