• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    function template
    <optional>

    std::operator<=

    namespace std {
      template <class T, class U>
      constexpr bool operator<=(const optional<T>& x, const optional<U>& y); // (1) C++17
    
      template <class T, class U>
      constexpr bool operator<=(const optional<T>& x, const U& y);           // (2) C++17
      template <class T, class U>
      constexpr bool operator<=(const U& x, const optional<T>& y);           // (3) C++17
    
      // operator<=>により、以下のオーバーロードが使用可能になる (C++20)
      template <class T>
      constexpr bool operator<=(const optional<T>& x, nullopt_t) noexcept;   // (4) C++17
      template <class T>
      constexpr bool operator<=(nullopt_t, const optional<T>& y) noexcept;   // (5) C++17
    }
    

    概要

    optionalにおいて、左辺が右辺以下かの判定を行う。

    要件

    • (1), (2), (3) : 型Tと型U<=演算子で比較可能であること

    戻り値

    • (1) : xyがどちらも有効値を持っていれば、有効値同士を<=演算子で比較した結果を返す。xが有効値を持っていなければtrueを返す。yが有効値を持っていなければfalseを返す
    • (2) : return x.has_value() ? x.value() <= v : true;
    • (3) : return y.has_value() ? x <= y.value() : false;
    • (4) : !x.has_value()を返す
    • (5) : trueを返す

    #include <cassert>
    #include <optional>
    
    int main()
    {
      // optionalオブジェクト同士の比較
      {
        std::optional<int> a = 1;
        std::optional<int> b = 3;
        std::optional<int> none;
    
        assert(a <= b);
        assert(!(a <= none));
        assert(none <= a);
      }
    
      // optionalオブジェクトとnulloptの比較
      {
        std::optional<int> p = 3;
        std::optional<int> none;
    
        assert(!(p <= std::nullopt));
        assert(none <= std::nullopt);
    
        assert(std::nullopt <= p);
        assert(std::nullopt <= none);
      }
    
      // optionalオブジェクトと有効値の比較
      {
        std::optional<int> p = 1;
        std::optional<int> none;
    
        assert(p <= 3);
        assert(0 <= p);
    
        assert(none <= 3);
        assert(!(3 <= none));
      }
    }
    

    出力

    バージョン

    言語

    • C++17

    処理系

    参照