GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::operator!= - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. optional
  3. optional
  4. operator!=

最終更新日時: 2026年09月11日 13時06分31秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<optional>

std::operator!=(C++17)

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 y) noexcept; // (4) C++17
  template <class T>
  constexpr bool operator!=(nullopt_t x, const optional<T>& y) noexcept; // (5) C++17
}

概要

optionalオブジェクトの非等値比較を行う。

テンプレートパラメータ制約

  • (1), (2), (3) : 型Tが!=で比較可能であること
  • (2), (3) : 比較する相手の型がoptionalの特殊化でないこと

戻り値

!(x == y)

例

#include <cassert>
#include <optional>

int main()
{
  // optionalオブジェクト同士の比較
  {
    std::optional<int> a = 3;
    std::optional<int> b = 1;
    std::optional<int> c = 3;
    std::optional<int> none;

    assert(a != b);
    assert(!(a != c));
    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 = 3;
    std::optional<int> none;

    assert(p != 1);
    assert(!(3 != p));

    assert(none != 1);
    assert(1 != none);
  }
}

出力

バージョン

言語

  • C++17

処理系

  • Clang: 4.0.1 ✅
  • GCC: 7.2 ✅
  • Visual C++: ??

参照

  • LWG Issue 2934. optional<const T> doesn't compare with T
  • P1614R2 The Mothership has Landed
    • C++20での三方比較演算子の追加と、関連する演算子の自動導出
  • LWG Issue 4072. std::optional comparisons: constrain harder
    • C++26で、optionalと値の比較演算子の制約に、相手の型がoptionalの特殊化でないことが追加された(optional同士の比較がこのオーバーロードに解決されるのを防ぐ)
  • LWG Issue 4370. Comparison of optional<T> to T may be ill-formed
    • C++26で、効果が三項演算子形式(x.has_value() ? *x == v : false)からif文形式へ変更された。比較結果がbool以外の型を返す場合に三項演算子で共通型が得られず不適格となる問題を防ぐもの(cpprefjpの戻り値の記述はもともとこの意味を表している)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.