Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
template_metaprogramming_ru.docx
Скачиваний:
12
Добавлен:
01.07.2025
Размер:
774 Кб
Скачать
☆

Запрашиваемые алгоритмы

Данный вид алгоритмов позволяет пользоватю формировать «запросы» поиска элемента в последовательности.

Данные алгоритмы возвращают итераторы или значения, что соответствуют STL алгоритмам с аналогичными именами.

Следующая таблица описывает заправшиваемые алгоритмы для последовательностей MPL. Как и в соответствующих алгоритмах STL, предикатом сравнения (компоратором) по умолчанию является mpl::less<_, _>.

Metafunction

Result ::type

Complexity

mpl::find<seq, T>

An iterator to the first occurrence of T in seq, or mpl::end<seq>::type if not found.

Linear.

mpl::find_if<seq, T, pred>

An iterator to the first element of seq that satisfies predicate pred, or mpl::end<seq>::type if not found.

Linear.

mpl::contains<seq, T>

True iff seq contains T.

Linear.

mpl::count<seq, T>

The number of occurrences of T in seq.

Linear.

mpl::count_if<seq, pred>

The number of elements in seq that satisfy predicate pred.

Linear.

mpl::equal<seq1, seq2>

True iff seq1 and seq2 contain the same elements in the same order.

Linear.

mpl::lower_bound< seq, T , compare >

The earliest order-preserving position at which T could be inserted in a sequence seq sorted according to comparison compare.

Logarithmic in invocations to compare. Logarithmic traversal of Random Access Sequences; linear traversal otherwise.

mpl::upper_bound< seq, T , compare >

The latest order-preserving position at which T could be inserted in a sequence seq sorted according to comparison compare.

Logarithmic in invocations to compare. Logarithmic traversal of Random Access Sequences; linear traversal otherwise.

mpl::max_element< seq , compare >

The first position i in seq such that for all positions j: mpl::apply< compare , mpl::deref<i>::type , mpl::deref<j>::type >::type::value == false

Linear.

mpl::min_element< seq , compare >

The first position i in seq such that for all positions j: mpl::apply< compare , mpl::deref<j>::type , mpl::deref<i>::type >::type::value == false

Linear.

Последовательности (Алгоритмы, создающие последовательности)

Все алгоритмы MPL для создания последовательностей организовны следующим образом:

  • Для каждого алгоритма хххх существует версия reverse_xxxx, которая принимает те же аргументы, но работает с элементами входной последовательности в обратном порядке.

  • Последний аргумент алгоритма является опциональной вставкой (inserter).

  • Если вставка не указана:

    • Если последовательность Seq является back_* расширяемый, то в результате будет вызвана:

mpl::back_inserter<mpl::clear<Seq>::type>

В противном случае:

mpl::front_inserter<mpl::clear<Seq>::type>

В следующих примерах, V123 указывает тип «вектор свойств», что эквивалентно mpl::vector_c<int, 1,2,3>. Аналогичным образом, l876 указывает тип эквивалентный mpl::list_c <int, 8,7,6>.

// starting sequences

typedef mpl::vector_c<int, 1, 2, 3> v123;

typedef mpl::list_c<int, 1, 2, 3> l123;

// transformation

typedef mpl::plus<_1, mpl::int_<5>> add5;

// using the default inserters

typedef mpl::transform<v123, add5>::type v678;

typedef mpl::transform<l123, add5>::type l678;

typedef mpl::reverse_transform<v123, add5>::type v876;

typedef mpl::reverse_transform<l123, add5>::type l876;

Таким образом, без явного указания вставки полается ожидаемый результат для front и back расришенных последовательностей.

Для того чтобы использовать версии с вставкой, однако, мы должны быть осведомлены о двух направлениях обхода и свойствах расширения последовательности, которая создается.

// this inserter is equivalent to the default, since v123 - vector

typedef mpl::transform<

v123, add5, mpl::back_inserter<mpl::vector<>>

>::type v678;

// also equivalent to the default, since l123 - list

typedef mpl::reverse_transform<

l123, add5, mpl::front_inserter<mpl::list<>>

>::type l678;

// properties of input sequence don't affect the result

typedef mpl::reverse_transform<

v123, add5, mpl::front_inserter<mpl::list<>>

>::type l678;

При использовании вставок для создании новой последовательности определяющую роль играет наличие back_* или front_* расширения для конкретной последовательности.

Правило по умолчанию: если пользователь явно не указал вид вставки, то используется та, для которой данная последовательность расширена.

Metafunction

Result::type

mpl::copy<seq>

The elements of seq.

mpl::copy_if<seq, pred>

The elements of seq that satisfy predicate pred.

mpl::remove<seq, T>

A sequence equivalent to seq, but without any elements identical to T.

mpl::remove_if<seq, pred>

Equivalent to seq, but without any elements that satisfy predicate pred.

mpl::replace<seq, old, new>

Equivalent to seq, but with all occurrences of old replaced by new.

mpl::replace_if<seq, pred, new>

Equivalent to seq, but with all elements satisfying pred replaced by new.

mpl::reverse<seq>

The elements of seq in reverse order.

mpl::transform<seq, unaryOp> mpl::transform<seq1, seq2, binaryOp>

The results of invoking unaryOp with consecutive elements of seq, or of invoking binaryOp with consecutive pairs of elements from seq1 and seq2.

mpl::unique<seq> mpl::unique<seq, equiv>

The sequence composed of the initial elements of every subrange of seq whose elements are all the same. If the equivalence relation equiv is supplied, it is used to determine sameness.

Алгоритмы создания последовательности имеют линейную сложность, и все, по умолчанию, возвращают последовательность эквивалентного типа, но с помощью соответствующей вставки тип результирующей последовательности может быть иным.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]