最終更新日時(UTC):
が更新

履歴 編集

function template
<optional>

std::swap (非メンバ関数)(C++17)

namespace std {
  template <class T>
  void swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y)));           // C++17
  template <class T>
  constexpr void swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y))); // C++23
}

概要

2つのoptionalオブジェクトを入れ替える。

効果

x.swap(y);

備考

Tがムーブ構築できない、もしくは型Tがswap可能でない場合、この関数はオーバーロード解決の候補から除外される。

#include <cassert>
#include <optional>

int main()
{
  // 状況1
  // 左辺と右辺の両方が有効値を持つ場合
  {
    std::optional<int> a = 3;
    std::optional<int> b = 1;

    // aとbを入れ替える
    std::swap(a, b);

    assert(a.value() == 1);
    assert(b.value() == 3);
  }

  // 状況2
  // 左辺が有効値を持ち、右辺が有効値を持たない場合
  {
    std::optional<int> a = 3;
    std::optional<int> b;

    // aとbを入れ替える
    std::swap(a, b);

    assert(!a.has_value());
    assert(b.has_value());
    assert(b.value() == 3);
  }

  // 状況3
  // 左辺が有効値を持たず、右辺が有効値を持つ場合
  {
    std::optional<int> a;
    std::optional<int> b = 3;

    // aとbを入れ替える
    std::swap(a, b);

    assert(a.has_value());
    assert(a.value() == 3);
    assert(!b.has_value());
  }

  // 状況4
  // 左辺と右辺の両方が有効値を持たない場合
  {
    std::optional<int> a;
    std::optional<int> b;

    // aとbを入れ替える
    std::swap(a, b);

    assert(!a.has_value());
    assert(!b.has_value());
  }
}

出力

バージョン

言語

  • C++17

処理系

参照