23 General utilities library [utilities]

23.14 Function objects [function.objects]

A function object type - это object type тип, который может быть типом postfix-expressionв вызове функции ([expr.call], [over.match.call]).222 A function object - объект типа функционального объекта. В тех местах, где можно было бы ожидать передачи указателя на функцию в алгоритмический шаблон (пункт [algorithms]), указывается интерфейс для приема объекта функции. Это не только заставляет алгоритмические шаблоны работать с указателями на функции, но также позволяет им работать с произвольными объектами функций.

Такой тип является указателем на функцию или типом класса, который имеет член operator() или тип класса, который имеет преобразование в указатель на функцию.

23.14.1 Header <functional> synopsis [functional.syn]

namespace std {
  // [func.invoke], invoke
  template <class F, class... Args>
    invoke_result_t<F, Args...> invoke(F&& f, Args&&... args)
      noexcept(is_nothrow_invocable_v<F, Args...>);

  // [refwrap], reference_­wrapper
  template <class T> class reference_wrapper;

  template <class T> reference_wrapper<T> ref(T&) noexcept;
  template <class T> reference_wrapper<const T> cref(const T&) noexcept;
  template <class T> void ref(const T&&) = delete;
  template <class T> void cref(const T&&) = delete;

  template <class T> reference_wrapper<T> ref(reference_wrapper<T>) noexcept;
  template <class T> reference_wrapper<const T> cref(reference_wrapper<T>) noexcept;

  // [arithmetic.operations], arithmetic operations
  template <class T = void> struct plus;
  template <class T = void> struct minus;
  template <class T = void> struct multiplies;
  template <class T = void> struct divides;
  template <class T = void> struct modulus;
  template <class T = void> struct negate;
  template <> struct plus<void>;
  template <> struct minus<void>;
  template <> struct multiplies<void>;
  template <> struct divides<void>;
  template <> struct modulus<void>;
  template <> struct negate<void>;

  // [comparisons], comparisons
  template <class T = void> struct equal_to;
  template <class T = void> struct not_equal_to;
  template <class T = void> struct greater;
  template <class T = void> struct less;
  template <class T = void> struct greater_equal;
  template <class T = void> struct less_equal;
  template <> struct equal_to<void>;
  template <> struct not_equal_to<void>;
  template <> struct greater<void>;
  template <> struct less<void>;
  template <> struct greater_equal<void>;
  template <> struct less_equal<void>;

  // [logical.operations], logical operations
  template <class T = void> struct logical_and;
  template <class T = void> struct logical_or;
  template <class T = void> struct logical_not;
  template <> struct logical_and<void>;
  template <> struct logical_or<void>;
  template <> struct logical_not<void>;

  // [bitwise.operations], bitwise operations
  template <class T = void> struct bit_and;
  template <class T = void> struct bit_or;
  template <class T = void> struct bit_xor;
  template <class T = void> struct bit_not;
  template <> struct bit_and<void>;
  template <> struct bit_or<void>;
  template <> struct bit_xor<void>;
  template <> struct bit_not<void>;

  // [func.not_fn], function template not_­fn
  template <class F>
    unspecified not_fn(F&& f);

  // [func.bind], bind
  template<class T> struct is_bind_expression;
  template<class T> struct is_placeholder;

  template<class F, class... BoundArgs>
    unspecified bind(F&&, BoundArgs&&...);
  template<class R, class F, class... BoundArgs>
    unspecified bind(F&&, BoundArgs&&...);

  namespace placeholders {
    // M is the implementation-defined number of placeholders
    see below _1;
    see below _2;
               .
               .
               .
    see below _M;
  }

  // [func.memfn], member function adaptors
  template<class R, class T>
    unspecified mem_fn(R T::*) noexcept;

  // [func.wrap], polymorphic function wrappers
  class bad_function_call;

  template<class> class function; // not defined
  template<class R, class... ArgTypes> class function<R(ArgTypes...)>;

  template<class R, class... ArgTypes>
    void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&) noexcept;

  template<class R, class... ArgTypes>
    bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept;
  template<class R, class... ArgTypes>
    bool operator==(nullptr_t, const function<R(ArgTypes...)>&) noexcept;
  template<class R, class... ArgTypes>
    bool operator!=(const function<R(ArgTypes...)>&, nullptr_t) noexcept;
  template<class R, class... ArgTypes>
    bool operator!=(nullptr_t, const function<R(ArgTypes...)>&) noexcept;

  // [func.search], searchers
  template<class ForwardIterator, class BinaryPredicate = equal_to<>>
    class default_searcher;

  template<class RandomAccessIterator,
           class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
           class BinaryPredicate = equal_to<>>
    class boyer_moore_searcher;

  template<class RandomAccessIterator,
           class Hash = hash<typename iterator_traits<RandomAccessIterator>::value_type>,
           class BinaryPredicate = equal_to<>>
    class boyer_moore_horspool_searcher;

  // [unord.hash], hash function primary template
  template <class T>
    struct hash;

  // [func.bind], function object binders
  template <class T>
    inline constexpr bool is_bind_expression_v = is_bind_expression<T>::value;
  template <class T>
    inline constexpr int is_placeholder_v = is_placeholder<T>::value;
}

[ Example: Если C ++ программа хочет иметь поэлементное сложение двух векторов a и b содержащее double и поместить результат в aэто можно сделать:

transform(a.begin(), a.end(), b.begin(), a.begin(), plus<double>());

end example]

[ Example: Чтобы отрицать каждый элемент a:

transform(a.begin(), a.end(), a.begin(), negate<double>());

end example]

23.14.2 Definitions [func.def]

К этому пункту применяются следующие определения:

A call signature - это имя возвращаемого типа, за которым следует список в скобках, разделенных запятыми, из нуля или более типов аргументов.

A callable type - это function object type указатель на член.

A callable object - объект вызываемого типа.

A call wrapper type - это тип, который содержит вызываемый объект и поддерживает операцию вызова, которая перенаправляет на этот объект.

A call wrapper - объект типа обертки вызова.

A target object - это вызываемый объект, удерживаемый оболочкой вызова.

23.14.3 Requirements [func.require]

Определите INVOKE(f, t1, t2, ..., tN) следующее:

  • (t1.*f)(t2, ..., tN) when f - указатель на функцию-член класса T и is_­base_­of_­v<T, decay_­t<decltype(t1)>> is true;

  • (t1.get().*f)(t2, ..., tN) when f - указатель на функцию-член класса T и decay_­t<decltype(t1)> является специализацией reference_­wrapper;

  • ((*t1).*f)(t2, ..., tN) when f является указателем на функцию-член класса T и t1 не удовлетворяет двум предыдущим элементам;

  • t1.*f когда N == 1 и f является указателем на член данных класса T и is_­base_­of_­v<T, decay_­t<decltype(t1)>> является true;

  • t1.get().*f когда N == 1 и f является указателем на член данных класса T и decay_­t<decltype(t1)> является специализацией reference_­wrapper;

  • (*t1).*f когда N == 1 и f является указателем на член данных класса T и t1 не удовлетворяет двум предыдущим элементам;

  • f(t1, t2, ..., tN) во всех остальных случаях.

Определите INVOKE<R>(f, t1, t2, ..., tN) как static_­cast<void>(INVOKE(f, t1, t2, ..., tN)) если бы R есть cv void, иначе INVOKE(f, t1, t2, ..., tN) неявно преобразовать в R.

Каждый call wrapper должен быть MoveConstructible. A forwarding call wrapper - это оболочка вызова, которая может быть вызвана с произвольным списком аргументов и доставляет аргументы обернутому вызываемому объекту в виде ссылок. Этот шаг пересылки должен гарантировать, что аргументы rvalue доставляются как ссылки rvalue, а аргументы lvalue доставляются как ссылки lvalue. A simple call wrapper - это оболочка переадресации вызовов, которая есть CopyConstructible и, CopyAssignable чей конструктор копирования, конструктор перемещения и оператор присваивания не генерируют исключения. [ Note: В типичной реализации оболочки переадресации вызовов имеют перегруженный оператор вызова функции вида

template<class... UnBoundArgs>
R operator()(UnBoundArgs&&... unbound_args) cv-qual;

end note]

23.14.4 Function template invoke [func.invoke]

template <class F, class... Args> invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) noexcept(is_nothrow_invocable_v<F, Args...>);

Returns: INVOKE(std​::​forward<F>(f), std​::​forward<Args>(args)...) ([func.require]).

23.14.5 Class template reference_­wrapper [refwrap]

namespace std {
  template <class T> class reference_wrapper {
  public :
    // types
    using type = T;

    // construct/copy/destroy
    reference_wrapper(T&) noexcept;
    reference_wrapper(T&&) = delete;     // do not bind to temporary objects
    reference_wrapper(const reference_wrapper& x) noexcept;

    // assignment
    reference_wrapper& operator=(const reference_wrapper& x) noexcept;

    // access
    operator T& () const noexcept;
    T& get() const noexcept;

    // invocation
    template <class... ArgTypes>
      invoke_result_t<T&, ArgTypes...>
      operator() (ArgTypes&&...) const;
  };

  template<class T>
    reference_wrapper(reference_wrapper<T>) -> reference_wrapper<T>;
}

reference_­wrapper<T> - это CopyConstructible и CopyAssignable оболочка вокруг ссылки на объект или функцию типа T.

reference_­wrapper<T> должен быть trivially copyable type.

23.14.5.1 reference_­wrapper construct/copy/destroy [refwrap.const]

reference_wrapper(T& t) noexcept;

Effects: Создает reference_­wrapper объект, хранящий ссылку на t.

reference_wrapper(const reference_wrapper& x) noexcept;

Effects: Создает reference_­wrapper объект, хранящий ссылку на x.get().

23.14.5.2 reference_­wrapper assignment [refwrap.assign]

reference_wrapper& operator=(const reference_wrapper& x) noexcept;

Postconditions: *this хранит ссылку на x.get().

23.14.5.3 reference_­wrapper access [refwrap.access]

operator T& () const noexcept;

Returns: Сохраненная ссылка.

T& get() const noexcept;

Returns: Сохраненная ссылка.

23.14.5.4 reference_­wrapper invocation [refwrap.invoke]

template <class... ArgTypes> invoke_result_t<T&, ArgTypes...> operator()(ArgTypes&&... args) const;

Returns: INVOKE(get(), std​::​forward<ArgTypes>(args)...). ([func.require])

23.14.5.5 reference_­wrapper helper functions [refwrap.helpers]

template <class T> reference_wrapper<T> ref(T& t) noexcept;

Returns: reference_­wrapper<T>(t).

template <class T> reference_wrapper<T> ref(reference_wrapper<T> t) noexcept;

Returns: ref(t.get()).

template <class T> reference_wrapper<const T> cref(const T& t) noexcept;

Returns: reference_­wrapper <const T>(t).

template <class T> reference_wrapper<const T> cref(reference_wrapper<T> t) noexcept;

Returns: cref(t.get()).

23.14.6 Arithmetic operations [arithmetic.operations]

Библиотека предоставляет базовые классы функциональных объектов для всех арифметических операторов языка ([expr.mul], [expr.add]).

23.14.6.1 Class template plus [arithmetic.operations.plus]

template <class T = void> struct plus { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x + y.

template <> struct plus<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) + std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) + std::forward<U>(u));

Returns: std​::​forward<T>(t) + std​::​forward<U>(u).

23.14.6.2 Class template minus [arithmetic.operations.minus]

template <class T = void> struct minus { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x - y.

template <> struct minus<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) - std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) - std::forward<U>(u));

Returns: std​::​forward<T>(t) - std​::​forward<U>(u).

23.14.6.3 Class template multiplies [arithmetic.operations.multiplies]

template <class T = void> struct multiplies { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x * y.

template <> struct multiplies<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) * std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) * std::forward<U>(u));

Returns: std​::​forward<T>(t) * std​::​forward<U>(u).

23.14.6.4 Class template divides [arithmetic.operations.divides]

template <class T = void> struct divides { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x / y.

template <> struct divides<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) / std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) / std::forward<U>(u));

Returns: std​::​forward<T>(t) / std​::​forward<U>(u).

23.14.6.5 Class template modulus [arithmetic.operations.modulus]

template <class T = void> struct modulus { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x % y.

template <> struct modulus<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) % std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) % std::forward<U>(u));

Returns: std​::​forward<T>(t) % std​::​forward<U>(u).

23.14.6.6 Class template negate [arithmetic.operations.negate]

template <class T = void> struct negate { constexpr T operator()(const T& x) const; };

constexpr T operator()(const T& x) const;

Returns: -x.

template <> struct negate<void> { template <class T> constexpr auto operator()(T&& t) const -> decltype(-std::forward<T>(t)); using is_transparent = unspecified; };

template <class T> constexpr auto operator()(T&& t) const -> decltype(-std::forward<T>(t));

Returns: -std​::​forward<T>(t).

23.14.7 Comparisons [comparisons]

Библиотека предоставляет базовые классы объектов функций для всех операторов сравнения на языке ([expr.rel], [expr.eq]).

Для шаблонов less, greater, less_­equalи greater_­equal, специализации для любого типа указателя дают строгий общий порядок , который соответствует числу тех специальностей , а также в соответствии с частичным порядком наложенного с помощью встроенного в операторах <, >, <=, >=. [ Note: Когда a < b хорошо определены для указателей a и b типа P, это означает (a < b) == less<P>(a, b), (a > b) == greater<P>(a, b)и так далее. ] Для шаблонных специализаций , , и , если оператор вызова вызывает встроенный оператор сравнения указателей, оператор вызова дает строгий общий порядок , который соответствует числу тех специализаций и также соответствует частичному порядка , навязанному тем встроенному операторы. end note less<void> greater<void>less_­equal<void> greater_­equal<void>

23.14.7.1 Class template equal_­to [comparisons.equal_to]

template <class T = void> struct equal_to { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x == y.

template <> struct equal_to<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) == std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) == std::forward<U>(u));

Returns: std​::​forward<T>(t) == std​::​forward<U>(u).

23.14.7.2 Class template not_­equal_­to [comparisons.not_equal_to]

template <class T = void> struct not_equal_to { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x != y.

template <> struct not_equal_to<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) != std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) != std::forward<U>(u));

Returns: std​::​forward<T>(t) != std​::​forward<U>(u).

23.14.7.3 Class template greater [comparisons.greater]

template <class T = void> struct greater { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x > y.

template <> struct greater<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) > std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) > std::forward<U>(u));

Returns: std​::​forward<T>(t) > std​::​forward<U>(u).

23.14.7.4 Class template less [comparisons.less]

template <class T = void> struct less { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x < y.

template <> struct less<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) < std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) < std::forward<U>(u));

Returns: std​::​forward<T>(t) < std​::​forward<U>(u).

23.14.7.5 Class template greater_­equal [comparisons.greater_equal]

template <class T = void> struct greater_equal { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x >= y.

template <> struct greater_equal<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) >= std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) >= std::forward<U>(u));

Returns: std​::​forward<T>(t) >= std​::​forward<U>(u).

23.14.7.6 Class template less_­equal [comparisons.less_equal]

template <class T = void> struct less_equal { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x <= y.

template <> struct less_equal<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) <= std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) <= std::forward<U>(u));

Returns: std​::​forward<T>(t) <= std​::​forward<U>(u).

23.14.8 Logical operations [logical.operations]

Библиотека содержит основные классы объектов функции для всех логических операторов в языке ([expr.log.and], [expr.log.or], [expr.unary.op]).

23.14.8.1 Class template logical_­and [logical.operations.and]

template <class T = void> struct logical_and { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x && y.

template <> struct logical_and<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) && std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) && std::forward<U>(u));

Returns: std​::​forward<T>(t) && std​::​forward<U>(u).

23.14.8.2 Class template logical_­or [logical.operations.or]

template <class T = void> struct logical_or { constexpr bool operator()(const T& x, const T& y) const; };

constexpr bool operator()(const T& x, const T& y) const;

Returns: x || y.

template <> struct logical_or<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) || std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) || std::forward<U>(u));

Returns: std​::​forward<T>(t) || std​::​forward<U>(u).

23.14.8.3 Class template logical_­not [logical.operations.not]

template <class T = void> struct logical_not { constexpr bool operator()(const T& x) const; };

constexpr bool operator()(const T& x) const;

Returns: !x.

template <> struct logical_not<void> { template <class T> constexpr auto operator()(T&& t) const -> decltype(!std::forward<T>(t)); using is_transparent = unspecified; };

template <class T> constexpr auto operator()(T&& t) const -> decltype(!std::forward<T>(t));

Returns: !std​::​forward<T>(t).

23.14.9 Bitwise operations [bitwise.operations]

Библиотека содержит основные классы объектов функции для всех операторов поразрядных на языке ([expr.bit.and], [expr.or], [expr.xor], [expr.unary.op]).

23.14.9.1 Class template bit_­and [bitwise.operations.and]

template <class T = void> struct bit_and { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x & y.

template <> struct bit_and<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) & std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) & std::forward<U>(u));

Returns: std​::​forward<T>(t) & std​::​forward<U>(u).

23.14.9.2 Class template bit_­or [bitwise.operations.or]

template <class T = void> struct bit_or { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x | y.

template <> struct bit_or<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) | std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) | std::forward<U>(u));

Returns: std​::​forward<T>(t) | std​::​forward<U>(u).

23.14.9.3 Class template bit_­xor [bitwise.operations.xor]

template <class T = void> struct bit_xor { constexpr T operator()(const T& x, const T& y) const; };

constexpr T operator()(const T& x, const T& y) const;

Returns: x ^ y.

template <> struct bit_xor<void> { template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) ^ std::forward<U>(u)); using is_transparent = unspecified; };

template <class T, class U> constexpr auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) ^ std::forward<U>(u));

Returns: std​::​forward<T>(t) ^ std​::​forward<U>(u).

23.14.9.4 Class template bit_­not [bitwise.operations.not]

template <class T = void> struct bit_not { constexpr T operator()(const T& x) const; };

constexpr T operator()(const T& x) const;

Returns: ~x.

template <> struct bit_not<void> { template <class T> constexpr auto operator()(T&& t) const -> decltype(~std::forward<T>(t)); using is_transparent = unspecified; };

template <class T> constexpr auto operator()(T&&) const -> decltype(~std::forward<T>(t));

Returns: ~std​::​forward<T>(t).

23.14.10 Function template not_­fn [func.not_fn]

template <class F> unspecified not_fn(F&& f);

Effects: Эквивалентен return call_­wrapper(std​::​forward<F>(f)); where call_­wrapper класс только для показа, определенный следующим образом:

class call_wrapper {
  using FD = decay_t<F>;
  FD fd;

  explicit call_wrapper(F&& f);

public:
  call_wrapper(call_wrapper&&) = default;
  call_wrapper(const call_wrapper&) = default;

  template<class... Args>
    auto operator()(Args&&...) &
      -> decltype(!declval<invoke_result_t<FD&, Args...>>());

  template<class... Args>
    auto operator()(Args&&...) const&
      -> decltype(!declval<invoke_result_t<const FD&, Args...>>());

  template<class... Args>
    auto operator()(Args&&...) &&
      -> decltype(!declval<invoke_result_t<FD, Args...>>());

  template<class... Args>
    auto operator()(Args&&...) const&&
      -> decltype(!declval<invoke_result_t<const FD, Args...>>());
};

explicit call_wrapper(F&& f);

Requires: FD должны удовлетворять требованиям MoveConstructible. is_­constructible_­v<FD, F> будет true. fd должен быть callable object.

Effects: Инициализируется fd из std​::​forward<F>(f).

Throws: Любое исключение, созданное при построении fd.

template<class... Args> auto operator()(Args&&... args) & -> decltype(!declval<invoke_result_t<FD&, Args...>>()); template<class... Args> auto operator()(Args&&... args) const& -> decltype(!declval<invoke_result_t<const FD&, Args...>>());

Effects: Эквивалентен:

return !INVOKE(fd, std::forward<Args>(args)...);              // see [func.require]

template<class... Args> auto operator()(Args&&... args) && -> decltype(!declval<invoke_result_t<FD, Args...>>()); template<class... Args> auto operator()(Args&&... args) const&& -> decltype(!declval<invoke_result_t<const FD, Args...>>());

Effects: Эквивалентен:

return !INVOKE(std::move(fd), std::forward<Args>(args)...);   // see [func.require]

23.14.11 Function object binders [func.bind]

В этом подпункте описывается унифицированный механизм привязки аргументов вызываемых объектов.

23.14.11.1 Class template is_­bind_­expression [func.bind.isbind]

namespace std {
  template<class T> struct is_bind_expression;  // see below
}

Шаблон класса is_­bind_­expression можно использовать для обнаружения функциональных объектов, сгенерированных bind. Шаблон функции bind используется is_­bind_­expression для обнаружения подвыражений.

Экземпляры is_­bind_­expression шаблона должны соответствовать UnaryTypeTrait требованиям. Реализация должна предоставлять определение, которое имеет базовую характеристику true_­type if T является типом, возвращаемым из bind, в противном случае он должен иметь базовую характеристику false_­type. Программа может специализировать этот шаблон для определяемого пользователем типа, T чтобы он имел базовую характеристику, true_­type указывающую, что T следует рассматривать как подвыражение в bind вызове.

23.14.11.2 Class template is_­placeholder [func.bind.isplace]

namespace std {
  template<class T> struct is_placeholder;      // see below
}

Шаблон класса is_­placeholder может быть использован для обнаружения стандартных заполнителей _­1, _­2и так далее. Шаблон функции bind используется is_­placeholder для обнаружения заполнителей.

Экземпляры is_­placeholder шаблона должны соответствовать UnaryTypeTrait требованиям. Реализация должна предоставлять определение, которое имеет базовую характеристику integral_­constant<int, J> if T is the type std​::​placeholders​::​_­J, в противном случае оно должно иметь базовую характеристику integral_­constant<int, 0>. Программа может специализировать этот шаблон для определяемого пользователем типа, T чтобы он имел базовую характеристику integral_­constant<int, N> with, N > 0 чтобы указать, что он T должен рассматриваться как тип-заполнитель.

23.14.11.3 Function template bind [func.bind.bind]

В следующем тексте:

  • FD это тип decay_­t<F>,

  • fd является l-значением типа, FD построенным из std​::​forward<F>(f),

  • Ti это ith тип в пакете параметров шаблона BoundArgs,

  • TDi это тип decay_­t<Ti>,

  • ti является ith аргументом в параметре функции пакета bound_­args,

  • tdi является l-значением типа, TDi построенным из std​::​forward<Ti>(ti),

  • Uj - jth выведенный тип UnBoundArgs&&... параметра оболочки переадресации вызовов, а

  • uj это jth аргумент , связанный с Uj.

template<class F, class... BoundArgs> unspecified bind(F&& f, BoundArgs&&... bound_args);

Requires: is_­constructible_­v<FD, F> будет true. Для каждого Ti в BoundArgs, is_­constructible_­v<TDi, Ti> должно быть true. INVOKE(fd, w1, w2, …, wN) ([func.require]) Должен быть допустимым выражением для некоторых значений w1, w2, ..., wN, где N имеет значение sizeof...(bound_­args). Квалификаторы cv cv оболочки вызова g, как указано ниже, не должны быть ни, volatile ни const volatile.

Returns: forwarding call wrapper g. Эффект g(u1, u2, …, uM) должен быть

INVOKE(fd, std::forward<V1>(v1), std::forward<V2>(v2), …, std::forward<VN>(vN))

где значения и типы связанных аргументов v1, v2..., vN определяются , как указано ниже. Конструктор копирования и конструктор перемещения оболочки перенаправляющего вызова должны вызывать исключение тогда и только тогда, когда соответствующий конструктор FD любого из типов TDi вызывает исключение.

Throws: Ничего, если конструкция fd или одно из значений не tdi вызывает исключение.

Remarks: Тип возвращаемого значения должен удовлетворять требованиям MoveConstructible. Если все FD и TDi удовлетворяют требованиям CopyConstructible, то тип возвращаемого значения должен удовлетворять требованиям CopyConstructible. [ Note: Это подразумевает, что все так FD и TDi есть MoveConstructible. ] end note

template<class R, class F, class... BoundArgs> unspecified bind(F&& f, BoundArgs&&... bound_args);

Requires: is_­constructible_­v<FD, F> будет true. Для каждого Ti в BoundArgs, is_­constructible_­v<TDi, Ti> должно быть true. INVOKE(fd, w1, w2, …, wN) должен быть допустимым выражением для некоторых значений w1, w2, ..., wN, где N имеет значение sizeof...(bound_­args). Квалификаторы cv cv оболочки вызова g, как указано ниже, не должны быть ни, volatile ни const volatile.

Returns: forwarding call wrapper g. Эффект g(u1, u2, …, uM) должен быть

INVOKE<R>(fd, std::forward<V1>(v1), std::forward<V2>(v2), …, std::forward<VN>(vN))

где значения и типы связанных аргументов v1, v2..., vN определяются , как указано ниже. Конструктор копирования и конструктор перемещения оболочки перенаправляющего вызова должны вызывать исключение тогда и только тогда, когда соответствующий конструктор FD любого из типов TDi вызывает исключение.

Throws: Ничего, если конструкция fd или одно из значений не tdi вызывает исключение.

Remarks: Тип возвращаемого значения должен удовлетворять требованиям MoveConstructible. Если все FD и TDi удовлетворяют требованиям CopyConstructible, то тип возвращаемого значения должен удовлетворять требованиям CopyConstructible. [ Note: Это подразумевает, что все так FD и TDi есть MoveConstructible. ] end note

Эти значения bound arguments v1, v2, ..., vN и соответствующие их типы V1, V2, ..., в VN зависимости от типов , TDi полученных от вызова bind и CV-классификаторов cv обертки вызова g следующим образом :

  • если TDi есть reference_­wrapper<T>, аргумент равен tdi.get() и его тип Vi равен T&;

  • если значение is_­bind_­expression_­v<TDi> равно true, аргумент равен tdi(std​::​forward<Uj>(uj)...) и его тип Vi равен invoke_­result_­t<TDi cv &, Uj...>&&;

  • если значение j в is_­placeholder_­v<TDi> не равен нулю, аргумент std​::​forward<Uj>(uj) и ее тип Vi является Uj&&;

  • в противном случае значение равно, tdi а его тип Vi - TDi cv &.

23.14.11.4 Placeholders [func.bind.place]

namespace std::placeholders {
  // M is the implementation-defined number of placeholders
  see below _1;
  see below _2;
              .
              .
              .
  see below _M;
}

Все типы заполнителей должны быть DefaultConstructible и CopyConstructible, а их конструкторы по умолчанию и конструкторы копирования / перемещения не должны вызывать исключений. Это определяется реализацией ли типы заполнителей являются CopyAssignable. CopyAssignable Операторы присваивания копий заполнителей не должны вызывать исключений.

Заполнители следует определять как:

inline constexpr unspecified _1{};

Если это не так, они должны быть объявлены как:

extern unspecified _1;

23.14.12 Function template mem_­fn [func.memfn]

template<class R, class T> unspecified mem_fn(R T::* pm) noexcept;

Returns: Простой call wrapper fn такой, что выражение fn(t, a2, ..., aN) эквивалентно INVOKE(pm, t, a2, ..., aN) ([func.require]).

23.14.13 Polymorphic function wrappers [func.wrap]

В этом подпункте описывается полиморфный класс-оболочка, который инкапсулирует произвольные вызываемые объекты.

23.14.13.1 Class bad_­function_­call [func.wrap.badcall]

Исключение типа bad_­function_­call выдается функциейfunction​::​operator() ([func.wrap.func.inv]), когда объект-оболочка функции не имеет цели.

namespace std {
  class bad_function_call : public exception {
  public:
    // [func.wrap.badcall.const], constructor
    bad_function_call() noexcept;
  };
}

23.14.13.1.1 bad_­function_­call constructor [func.wrap.badcall.const]

bad_function_call() noexcept;

Effects: Создает bad_­function_­call объект.

Postconditions: what() возвращает определяемый реализацией файл ntbs .

23.14.13.2 Class template function [func.wrap.func]

namespace std {
  template<class> class function; // not defined

  template<class R, class... ArgTypes>
  class function<R(ArgTypes...)> {
  public:
    using result_type = R;

    // [func.wrap.func.con], construct/copy/destroy
    function() noexcept;
    function(nullptr_t) noexcept;
    function(const function&);
    function(function&&);
    template<class F> function(F);

    function& operator=(const function&);
    function& operator=(function&&);
    function& operator=(nullptr_t) noexcept;
    template<class F> function& operator=(F&&);
    template<class F> function& operator=(reference_wrapper<F>) noexcept;

    ~function();

    // [func.wrap.func.mod], function modifiers
    void swap(function&) noexcept;

    // [func.wrap.func.cap], function capacity
    explicit operator bool() const noexcept;

    // [func.wrap.func.inv], function invocation
    R operator()(ArgTypes...) const;

    // [func.wrap.func.targ], function target access
    const type_info& target_type() const noexcept;
    template<class T>       T* target() noexcept;
    template<class T> const T* target() const noexcept;
  };

  template<class R, class... ArgTypes>
    function(R(*)(ArgTypes...)) -> function<R(ArgTypes...)>;

  template<class F> function(F) -> function<see below>;

  // [func.wrap.func.nullptr], Null pointer comparisons
  template <class R, class... ArgTypes>
    bool operator==(const function<R(ArgTypes...)>&, nullptr_t) noexcept;

  template <class R, class... ArgTypes>
    bool operator==(nullptr_t, const function<R(ArgTypes...)>&) noexcept;

  template <class R, class... ArgTypes>
    bool operator!=(const function<R(ArgTypes...)>&, nullptr_t) noexcept;

  template <class R, class... ArgTypes>
    bool operator!=(nullptr_t, const function<R(ArgTypes...)>&) noexcept;

  // [func.wrap.func.alg], specialized algorithms
  template <class R, class... ArgTypes>
    void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&) noexcept;
}

function Шаблон класса обеспечивает полиморфные упаковщики, обобщающие понятие указателя функции. Оболочки могут хранить, копировать и вызывать произвольные callable objects, заданные a call signature, что позволяет функциям быть первоклассными объектами.

A callable type F используется Lvalue-Callable для типов аргументов ArgTypes и типа возвращаемого значения, R если выражение INVOKE<R>(declval<F&>(), declval<ArgTypes>()...), рассматриваемое как a unevaluated operand, имеет правильный формат ([func.require]).

function Шаблон класса является call wrapper которого call signature является R(ArgTypes...).

[ Note: Типы, определенные в руководствах по вычетам, function могут измениться в будущих версиях этого международного стандарта. ]end note

23.14.13.2.1 function construct/copy/destroy [func.wrap.func.con]

function() noexcept;

Postconditions: !*this.

function(nullptr_t) noexcept;

Postconditions: !*this.

function(const function& f);

Postconditions: !*this если !f; в противном случае *this нацелена на копию f.target().

Throws: не должен генерировать исключения, если fцель является специализацией reference_­wrapper или указателем на функцию. В противном случае может вызвать bad_­alloc или любое исключение, созданное конструктором копирования сохраненного вызываемого объекта. [ Note: Реализациям рекомендуется избегать использования динамически выделяемой памяти для небольших вызываемых объектов, например, где fцелью является объект, содержащий только указатель или ссылку на объект и указатель на функцию-член. ] end note

function(function&& f);

Postconditions: Если !f, *this не имеют целей; в противном случае цель *this эквивалентна цели f до построения и f находится в допустимом состоянии с неопределенным значением.

Throws: не должен генерировать исключения, если fцель является специализацией reference_­wrapper или указателем на функцию. В противном случае может вызвать bad_­alloc или любое исключение, созданное конструктором копирования или перемещения сохраненного вызываемого объекта. [ Note: Реализациям рекомендуется избегать использования динамически выделяемой памяти для небольших вызываемых объектов, например, где fцелью является объект, содержащий только указатель или ссылку на объект и указатель на функцию-член. ] end note

template<class F> function(F f);

Requires: F будет CopyConstructible.

Remarks: Этот шаблон конструктора не должен участвовать в разрешении перегрузки, если только он не F предназначен Lvalue-Callable для типов аргументов ArgTypes... и типа возвращаемого значения R.

Postconditions: !*this если выполняется какое-либо из следующих условий:

  • f - значение указателя нулевой функции.

  • f - значение указателя на нулевой член.

  • F является экземпляром function шаблона класса, а !f.

В противном случае *this нацелена на копию, f инициализированную с помощью std​::​move(f). [ Note: Реализациям рекомендуется избегать использования динамически выделяемой памяти для небольших вызываемых объектов, например, где f объект, содержащий только указатель или ссылку на объект и указатель на функцию-член. ] end note

Throws: не должен генерировать исключения, если f это указатель на функцию или reference_­wrapper<T> для некоторых T. В противном случае может вызвать bad_­alloc или любое исключение, созданное конструктором Fкопирования или перемещения.

template<class F> function(F) -> function<see below>;

Remarks: Это руководство по выводу участвует в разрешении перегрузки только в том случае, если &F​::​operator() оно правильно сформировано, когда рассматривается как неоцененный операнд. В том случае, если decltype(&F​::​operator()) is имеет форму R(G​::​*)(A...) cv &opt noexceptopt для типа класса G, то выводимый тип имеет вид function<R(A...)>.

[Example:

void f() {
  int i{5};
  function g = [&](double) { return i; }; // deduces function<int(double)>
}

end example]

function& operator=(const function& f);

Effects: Как если бы function(f).swap(*this);

Returns: *this.

function& operator=(function&& f);

Effects: Заменяет цель *this на цель f.

Returns: *this.

function& operator=(nullptr_t) noexcept;

Effects: Если *this != nullptr, уничтожает цель this.

Postconditions: !(*this).

Returns: *this.

template<class F> function& operator=(F&& f);

Effects: Как будто по: function(std​::​forward<F>(f)).swap(*this);

Returns: *this.

Remarks: Этот оператор присваивания не должен участвовать в разрешении перегрузки, кроме decay_­t<F> как Lvalue-Callable для типов аргументов ArgTypes... и типа возвращаемого значения R.

template<class F> function& operator=(reference_wrapper<F> f) noexcept;

Effects: Как будто по: function(f).swap(*this);

Returns: *this.

~function();

Effects: Если *this != nullptr, уничтожает цель this.

23.14.13.2.2 function modifiers [func.wrap.func.mod]

void swap(function& other) noexcept;

Effects: меняет местами цели *this и other.

23.14.13.2.3 function capacity [func.wrap.func.cap]

explicit operator bool() const noexcept;

Returns: true если *this есть цель, иначе false.

23.14.13.2.4 function invocation [func.wrap.func.inv]

R operator()(ArgTypes... args) const;

Returns: INVOKE<R>(f, std​::​forward<ArgTypes>(args)...) ([func.require]), где f - target object оф *this.

Throws: bad_­function_­call если !*this; в противном случае - любое исключение, созданное обернутым вызываемым объектом.

23.14.13.2.5 function target access [func.wrap.func.targ]

const type_info& target_type() const noexcept;

Returns: Если *this есть цель типа T, typeid(T); в противном случае typeid(void).

template<class T> T* target() noexcept; template<class T> const T* target() const noexcept;

Returns: Если target_­type() == typeid(T) указатель на сохраненную функцию target; в противном случае - нулевой указатель.

23.14.13.2.6 null pointer comparison functions [func.wrap.func.nullptr]

template <class R, class... ArgTypes> bool operator==(const function<R(ArgTypes...)>& f, nullptr_t) noexcept; template <class R, class... ArgTypes> bool operator==(nullptr_t, const function<R(ArgTypes...)>& f) noexcept;

Returns: !f.

template <class R, class... ArgTypes> bool operator!=(const function<R(ArgTypes...)>& f, nullptr_t) noexcept; template <class R, class... ArgTypes> bool operator!=(nullptr_t, const function<R(ArgTypes...)>& f) noexcept;

Returns: (bool)f.

23.14.13.2.7 specialized algorithms [func.wrap.func.alg]

template<class R, class... ArgTypes> void swap(function<R(ArgTypes...)>& f1, function<R(ArgTypes...)>& f2) noexcept;

Effects: Как будто по: f1.swap(f2);

23.14.14 Searchers [func.search]

В этом подпункте предусмотрены function object types операции, которые ищут последовательность [pat_first, pat_­last) в другой последовательности, [first, last) которая предоставляется оператору вызова функции объекта. Первая последовательность (шаблон для поиска) предоставляется конструктору объекта, а вторая (последовательность для поиска) предоставляется оператору вызова функции.

Каждая специализация шаблона класса , указанного в настоящем подпункте , [func.search] должны отвечать CopyConstructible и CopyAssignable требованиям. Параметры шаблона с именем

  • ForwardIterator,

  • ForwardIterator1,

  • ForwardIterator2,

  • RandomAccessIterator,

  • RandomAccessIterator1,

  • RandomAccessIterator2, а также

  • BinaryPredicate

шаблонов, указанных в этом подпункте, [func.search] должны соответствовать тем же требованиям и семантике, что и в [algorithms.general]. Названные параметры шаблона Hash должны соответствовать требованиям, указанным в [hash.requirements].

Программа поиска Бойера-Мура реализует алгоритм поиска Бойера-Мура. Программа поиска Boyer-Moore-Horspool реализует алгоритм поиска Boyer-Moore-Horspool. В общем, поисковик Бойера-Мура будет использовать больше памяти и работать лучше, чем Бойер-Мур-Хорспул.

23.14.14.1 Class template default_­searcher [func.search.default]

template <class ForwardIterator1, class BinaryPredicate = equal_to<>>
  class default_searcher {
  public:
    default_searcher(ForwardIterator1 pat_first, ForwardIterator1 pat_last,
                     BinaryPredicate pred = BinaryPredicate());

    template <class ForwardIterator2>
      pair<ForwardIterator2, ForwardIterator2>
        operator()(ForwardIterator2 first, ForwardIterator2 last) const;

  private:
    ForwardIterator1 pat_first_;        // exposition only
    ForwardIterator1 pat_last_;         // exposition only
    BinaryPredicate pred_;              // exposition only
  };

default_searcher(ForwardIterator pat_first, ForwardIterator pat_last, BinaryPredicate pred = BinaryPredicate());

Effects: Создает default_­searcher объект, инициализируясь pat_­first_­ с помощью pat_­first, pat_­last_­с помощью pat_­lastи pred_­ с помощью pred.

Throws: Любое исключение, созданное конструктором копирования BinaryPredicate или ForwardIterator1.

template<class ForwardIterator2> pair<ForwardIterator2, ForwardIterator2> operator()(ForwardIterator2 first, ForwardIterator2 last) const;

Effects: Возвращает пару итераторов i и j таких, что

  • i == search(first, last, pat_­first_­, pat_­last_­, pred_­), а также

  • если i == last, то j == lastиначе j == next(i, distance(pat_­first_­, pat_­last_­)).

23.14.14.2 Class template boyer_­moore_­searcher [func.search.bm]

template <class RandomAccessIterator1,
          class Hash = hash<typename iterator_traits<RandomAccessIterator1>::value_type>,
          class BinaryPredicate = equal_to<>>
  class boyer_moore_searcher {
  public:
    boyer_moore_searcher(RandomAccessIterator1 pat_first,
                         RandomAccessIterator1 pat_last,
                         Hash hf = Hash(),
                         BinaryPredicate pred = BinaryPredicate());

    template <class RandomAccessIterator2>
      pair<RandomAccessIterator2, RandomAccessIterator2>
        operator()(RandomAccessIterator2 first, RandomAccessIterator2 last) const;

  private:
    RandomAccessIterator1 pat_first_;   // exposition only
    RandomAccessIterator1 pat_last_;    // exposition only
    Hash hash_;                         // exposition only
    BinaryPredicate pred_;              // exposition only
  };

boyer_moore_searcher(RandomAccessIterator1 pat_first, RandomAccessIterator1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate());

Requires: Тип значения RandomAccessIterator1 должен соответствовать DefaultConstructible требованиям, CopyConstructible требованиям и CopyAssignable требованиям.

Requires: Для любых двух значений A и B типа iterator_­traits<RandomAccessIterator1>​::​value_­type, если pred(A, B) == true, то hf(A) == hf(B) должно быть true.

Effects: Создает boyer_­moore_­searcher объект, инициализируясь pat_­first_­ с pat_­first, pat_­last_­ с pat_­last, hash_­ с hfи pred_­ с pred.

Throws: Любое исключение брошенная копию конструктора RandomAccessIterator1, или с помощью конструктора по умолчанию, конструктор копирования или оператор присваивания копии типа ценностной RandomAccessIterator1или конструктор копирования или operator() из BinaryPredicate или Hash. Может bad_­alloc вызвать ошибку, если не может быть выделена дополнительная память, необходимая для внутренних структур данных.

template <class RandomAccessIterator2> pair<RandomAccessIterator2, RandomAccessIterator2> operator()(RandomAccessIterator2 first, RandomAccessIterator2 last) const;

Requires: RandomAccessIterator1 и RandomAccessIterator2 должен иметь один и тот же тип значения.

Effects: Находит подпоследовательность равных значений в последовательности.

Returns: Пара итераторов i и j такие, что

  • i - это первый итератор в диапазоне, [first, last - (pat_­last_­ - pat_­first_­)) такой, что для каждого неотрицательного целого числа, n меньшего, чем pat_­last_­ - pat_­first_­ выполняется следующее условие:, pred(*(i + n), *(pat_­first_­ + n)) != falseи

  • j == next(i, distance(pat_­first_­, pat_­last_­)).

Возвращает, make_­pair(first, first) если [pat_­first_­, pat_­last_­) пусто, в противном случае возвращает, make_­pair(last, last) если такой итератор не найден.

Complexity: В большинстве (last - first) * (pat_­last_­ - pat_­first_­) случаев применения предиката.

23.14.14.3 Class template boyer_­moore_­horspool_­searcher [func.search.bmh]

template <class RandomAccessIterator1,
          class Hash = hash<typename iterator_traits<RandomAccessIterator1>::value_type>,
          class BinaryPredicate = equal_to<>>
  class boyer_moore_horspool_searcher {
  public:
    boyer_moore_horspool_searcher(RandomAccessIterator1 pat_first,
                                  RandomAccessIterator1 pat_last,
                                  Hash hf = Hash(),
                                  BinaryPredicate pred = BinaryPredicate());

    template <class RandomAccessIterator2>
      pair<RandomAccessIterator2, RandomAccessIterator2>
        operator()(RandomAccessIterator2 first, RandomAccessIterator2 last) const;

  private:
    RandomAccessIterator1 pat_first_;   // exposition only
    RandomAccessIterator1 pat_last_;    // exposition only
    Hash hash_;                         // exposition only
    BinaryPredicate pred_;              // exposition only
  };

boyer_moore_horspool_searcher(RandomAccessIterator1 pat_first, RandomAccessIterator1 pat_last, Hash hf = Hash(), BinaryPredicate pred = BinaryPredicate());

Requires: Тип значения RandomAccessIterator1 должны удовлетворять DefaultConstructible, CopyConstructibleи CopyAssignable требования.

Requires: Для любых двух значений A и B типа iterator_­traits<RandomAccessIterator1>​::​value_­type, если pred(A, B) == true, то hf(A) == hf(B) должно быть true.

Effects: Создает boyer_­moore_­horspool_­searcher объект, инициализируясь pat_­first_­ с pat_­first, pat_­last_­ с pat_­last, hash_­ с hfи pred_­ с pred.

Throws: Любое исключение брошенная копию конструктора RandomAccessIterator1, или с помощью конструктора по умолчанию, конструктор копирования или оператор присваивания копии типа ценностной RandomAccessIterator1 или копирующего конструктора или operator() из BinaryPredicate или Hash. Может bad_­alloc вызвать ошибку, если не может быть выделена дополнительная память, необходимая для внутренних структур данных.

template <class RandomAccessIterator2> pair<RandomAccessIterator2, RandomAccessIterator2> operator()(RandomAccessIterator2 first, RandomAccessIterator2 last) const;

Requires: RandomAccessIterator1 и RandomAccessIterator2 должен иметь один и тот же тип значения.

Effects: Находит подпоследовательность равных значений в последовательности.

Returns: Пара итераторов i и j такие, что

  • i - это первый итератор i в диапазоне, [first, last - (pat_­last_­ - pat_­first_­)) такой, что для каждого неотрицательного целого числа, n меньшего, чем pat_­last_­ - pat_­first_­ выполняется следующее условие:, pred(*(i + n), *(pat_­first_­ + n)) != falseи

  • j == next(i, distance(pat_­first_­, pat_­last_­)).

Возвращает, make_­pair(first, first) если [pat_­first_­, pat_­last_­) пусто, в противном случае возвращает, make_­pair(last, last) если такой итератор не найден.

Complexity: В большинстве (last - first) * (pat_­last_­ - pat_­first_­) случаев применения предиката.

23.14.15 Class template hash [unord.hash]

Неупорядоченные ассоциативные контейнеры, определенные в [unord] специализациях класса template hash ([functional.syn]) в качестве хэш-функции по умолчанию.

Каждая специализация hash включена или отключена, как описано ниже. [ Note: Включенные специализации соответствуют требованиям Hash, а отключенные - нет. ] Каждый заголовок, который объявляет шаблон, предоставляет включенные специализации для и всех cv-неквалифицированных типов арифметики, перечисления и указателя. Для любого типа, для которого ни библиотека, ни пользователь не предоставляют явную или частичную специализацию шаблона класса , отключен.end note hash hash nullptr_­t Key hashhash<Key>

Если библиотека предоставляет явную или частичную специализацию hash<Key>, эта специализация включена, если не указано иное, и ее функции-члены, noexcept если не указано иное.

Если H инвалид специализации hash, эти значения false: is_­default_­constructible_­v<H>, is_­copy_­constructible_­v<H>, is_­move_­constructible_­v<H>, is_­copy_­assignable_­v<H>, и is_­move_­assignable_­v<H>. Инвалидов специализации hash нет function object types. [ Note: Это означает, что специализация hash существует, но любые попытки использовать ее как a Hash будут плохо сформированы. ]end note

Включенная специализация hash<Key> :

  • удовлетворяют Hash requirements, с Key как тип аргумента вызова функции, то DefaultConstructible requirements, то CopyAssignable requirements,

  • быть swappable для lvalues,

  • удовлетворяют требованию, что if k1 == k2 is true, h(k1) == h(k2) is также true, where h is объект типа hash<Key> и k1 and k2 are объекты типа Key;

  • удовлетворять требованию, согласно которому выражение h(k), где h является объектом типа hash<Key> и k является объектом типа Key, не должно вызывать исключения, если только hash<Key> это не определенная пользователем специализация, которая зависит по крайней мере от одного определяемого пользователем типа.