100 lines · cpp
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9// UNSUPPORTED: c++03, c++11, c++1410// <optional>11 12// template <class U> constexpr T optional<T>::value_or(U&& v) &&;13 14#include <optional>15#include <type_traits>16#include <cassert>17 18#include "test_macros.h"19 20using std::optional;21using std::in_place_t;22using std::in_place;23 24struct Y25{26 int i_;27 28 constexpr Y(int i) : i_(i) {}29};30 31struct X32{33 int i_;34 35 constexpr X(int i) : i_(i) {}36 constexpr X(X&& x) : i_(x.i_) {x.i_ = 0;}37 constexpr X(const Y& y) : i_(y.i_) {}38 constexpr X(Y&& y) : i_(y.i_+1) {}39 friend constexpr bool operator==(const X& x, const X& y)40 {return x.i_ == y.i_;}41};42 43struct Z {44 int i_, j_;45 constexpr Z(int i, int j) : i_(i), j_(j) {}46 friend constexpr bool operator==(const Z& z1, const Z& z2) { return z1.i_ == z2.i_ && z1.j_ == z2.j_; }47};48 49constexpr int test()50{51 {52 optional<X> opt(in_place, 2);53 Y y(3);54 assert(std::move(opt).value_or(y) == 2);55 assert(*opt == 0);56 }57 {58 optional<X> opt(in_place, 2);59 assert(std::move(opt).value_or(Y(3)) == 2);60 assert(*opt == 0);61 }62 {63 optional<X> opt;64 Y y(3);65 assert(std::move(opt).value_or(y) == 3);66 assert(!opt);67 }68 {69 optional<X> opt;70 assert(std::move(opt).value_or(Y(3)) == 4);71 assert(!opt);72 }73 {74 optional<X> opt;75 assert(std::move(opt).value_or({Y(3)}) == 4);76 assert(!opt);77 }78 {79 optional<Z> opt;80 assert((std::move(opt).value_or({2, 3}) == Z{2, 3}));81 assert(!opt);82 }83#if TEST_STD_VER >= 2684 {85 int y = 2;86 optional<int&> opt;87 assert(std::move(opt).value_or(y) == 2);88 assert(!opt);89 }90#endif91 return 0;92}93 94int main(int, char**)95{96 static_assert(test() == 0);97 98 return 0;99}100