close
Пространства имён
Варианты
Действия

Заголовочный файл стандартной библиотеки <optional> (C++17)

Материал из cppreference.com
 
 
Заголовочные файлы стандартной библиотеки
Языковая поддержка
Концепты
<concepts> (C++20)
Диагностика
<system_error> (C++11)

Управление памятью
<memory_resource> (C++17)  
Метапрограммирование
<type_traits> (C++11)
<ratio> (C++11)
Общие утилиты
<utility>
<tuple> (C++11)
<optional> (C++17)
<variant> (C++17)
<any> (C++17)
<expected> (C++23)
<bitset>

<charconv> (C++17)
<format> (C++20)
<bit> (C++20)

Строки
<cuchar> (C++11)

Контейнеры
<flat_set> (C++23)
<span> (C++20)
<mdspan> (C++23)

Итераторы
<iterator>
Диапазоны
<ranges> (C++20)
<generator> (C++23)
Алгоритмы
Числа
<cfenv> (C++11)
<complex>
<numbers> (C++20)

Время
<chrono> (C++11)
Локализация
<codecvt> (C++11/17*)
Ввод/вывод
<filesystem> (C++17)
<cstdio>
<cinttypes> (C++11)
<strstream> (C++98*)
Регулярные выражения
<regex> (C++11)
Поддержка конкуренции
<stop_token> (C++20)
<thread> (C++11)
<atomic> (C++11)
<stdatomic.h> (C++23)
<mutex> (C++11)
<shared_mutex> (C++14)
<condition_variable> (C++11)  
<semaphore> (C++20)
<latch> (C++20)
<barrier> (C++20)
<future> (C++11)

Совместимость с C
<cstdbool> (C++11/17/20*)  
<ccomplex> (C++11/17/20*)
<ctgmath> (C++11/17/20*)

<cstdalign> (C++11/17/20*)

<ciso646> (до C++20)

 

Включает

(C++20)
Поддержка оператора трёхстороннего сравнения [править]

(C++17)
обёртка, которая может содержать или не содержать объект
(шаблон класса) [править]
исключение, указывающее на доступ на проверку к optional, не содержащему значения
(класс) [править]
поддержка хэширования для std::optional
(специализация шаблона класса) [править]
(C++17)
индикатор типа optional с неинициализированным состоянием
(класс) [править]
Предварительные объявления
Определены в заголовочном файле <functional>
(C++11)
Объект хеш-функции
(шаблон класса) [править]

Константы

(C++17)
объект типа nullopt_t
(константа) [править]

Функции

Сравнение
(C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20)
сравнивает объекты optional
(шаблон функции) [править]
Специализированные алгоритмы
специализация алгоритма std::swap
(шаблон функции) [править]
создаёт объект optional
(шаблон функции) [править]

Краткое описание

#include <compare>

namespace std {
  // шаблонный класс optional
  template<class T>
    class optional;

  // индикатор состояния отсутствия значения
  struct nullopt_t{/* смотрите описание */};
  inline constexpr nullopt_t nullopt(/* неопределено */);

  // класс bad_optional_access
  class bad_optional_access;

  // операторы отношения
  template<class T, class U>
    constexpr bool operator==(const optional<T>&, const optional<U>&);
  template<class T, class U>
    constexpr bool operator!=(const optional<T>&, const optional<U>&);
  template<class T, class U>
    constexpr bool operator<(const optional<T>&, const optional<U>&);
  template<class T, class U>
    constexpr bool operator>(const optional<T>&, const optional<U>&);
  template<class T, class U>
    constexpr bool operator<=(const optional<T>&, const optional<U>&);
  template<class T, class U>
    constexpr bool operator>=(const optional<T>&, const optional<U>&);
  template<class T, three_way_comparable_with<T> U>
    constexpr compare_three_way_result_t<T,U>
      operator<=>(const optional<T>&, const optional<U>&);

  // сравнение с nullopt
  template<class T> constexpr bool operator==(const optional<T>&, nullopt_t) noexcept;
  template<class T>
    constexpr strong_ordering operator<=>(const optional<T>&, nullopt_t) noexcept;

  // сравнение с T
  template<class T, class U> constexpr bool operator==(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator==(const T&, const optional<U>&);
  template<class T, class U> constexpr bool operator!=(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator!=(const T&, const optional<U>&);
  template<class T, class U> constexpr bool operator<(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator<(const T&, const optional<U>&);
  template<class T, class U> constexpr bool operator>(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator>(const T&, const optional<U>&);
  template<class T, class U> constexpr bool operator<=(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator<=(const T&, const optional<U>&);
  template<class T, class U> constexpr bool operator>=(const optional<T>&, const U&);
  template<class T, class U> constexpr bool operator>=(const T&, const optional<U>&);
  template<class T, three_way_comparable_with<T> U>
    constexpr compare_three_way_result_t<T,U>
      operator<=>(const optional<T>&, const U&);

  // специализированные алгоритмы
  template<class T>
    constexpr void swap(optional<T>&, optional<T>&) noexcept(/* смотрите описание */);

  template<class T>
    constexpr optional</* смотрите описание */> make_optional(T&&);
  template<class T, class... Args>
    constexpr optional<T> make_optional(Args&&... args);
  template<class T, class U, class... Args>
    constexpr optional<T> make_optional(initializer_list<U> il, Args&&... args);

  // поддержка хеширования
  template<class T> struct hash;
  template<class T> struct hash<optional<T>>;
}

Шаблонный класс std::optional

namespace std {
  template<class T>
  class optional {
  public:
    using value_type = T;

    // конструкторы
    constexpr optional() noexcept;
    constexpr optional(nullopt_t) noexcept;
    constexpr optional(const optional&);
    constexpr optional(optional&&) noexcept(/* смотрите описание */);
    template<class... Args>
      constexpr explicit optional(in_place_t, Args&&...);
    template<class U, class... Args>
      constexpr explicit optional(in_place_t, initializer_list<U>, Args&&...);
    template<class U = T>
      constexpr explicit(/* смотрите описание */) optional(U&&);
    template<class U>
      constexpr explicit(/* смотрите описание */) optional(const optional<U>&);
    template<class U>
      constexpr explicit(/* смотрите описание */) optional(optional<U>&&);

    // деструкторы
    constexpr ~optional();

    // присваивание
    constexpr optional& operator=(nullopt_t) noexcept;
    constexpr optional& operator=(const optional&);
    constexpr optional& operator=(optional&&) noexcept(/* смотрите описание */);
    template<class U = T> constexpr optional& operator=(U&&);
    template<class U> constexpr optional& operator=(const optional<U>&);
    template<class U> constexpr optional& operator=(optional<U>&&);
    template<class... Args> constexpr T& emplace(Args&&...);
    template<class U, class... Args> constexpr T& emplace(initializer_list<U>, Args&&...);

    // обмен
    constexpr void swap(optional&) noexcept(/* смотрите описание */);

    // наблюдатели
    constexpr const T* operator->() const noexcept;
    constexpr T* operator->() noexcept;
    constexpr const T& operator*() const& noexcept;
    constexpr T& operator*() & noexcept;
    constexpr T&& operator*() && noexcept;
    constexpr const T&& operator*() const&& noexcept;
    constexpr explicit operator bool() const noexcept;
    constexpr bool has_value() const noexcept;
    constexpr const T& value() const&;
    constexpr T& value() &;
    constexpr T&& value() &&;
    constexpr const T&& value() const&&;
    template<class U> constexpr T value_or(U&&) const&;
    template<class U> constexpr T value_or(U&&) &&;

    // монадические операции
    template <class F> constexpr auto and_then(F&& f) &;
    template <class F> constexpr auto and_then(F&& f) &&;
    template <class F> constexpr auto and_then(F&& f) const&;
    template <class F> constexpr auto and_then(F&& f) const&&;
    template <class F> constexpr auto transform(F&& f) &;
    template <class F> constexpr auto transform(F&& f) &&;
    template <class F> constexpr auto transform(F&& f) const&;
    template <class F> constexpr auto transform(F&& f) const&&;
    template <class F> constexpr optional or_else(F&& f) &&;
    template <class F> constexpr optional or_else(F&& f) const&;

    // модификаторы
    constexpr void reset() noexcept;

  private:
    T *val;         // только для пояснения
  };

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