81 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// <utility>10 11// template <class T1, class T2> struct pair12// void swap(const pair& p) const;13 14// UNSUPPORTED: c++03, c++11, c++14, c++17, c++2015 16#include <cassert>17#include <utility>18 19#include "test_macros.h"20 21// Remarks: The expression inside noexcept is equivalent to22// is_nothrow_swappable_v<const first_type> && is_nothrow_swappable_v<const second_type> for the second overload.23template <class T>24concept ConstMemberSwapNoexcept =25 requires(const T& t1, const T& t2) {26 { t1.swap(t2) } noexcept;27 };28 29template <bool canThrow>30struct SwapMayThrow {};31 32template <bool canThrow>33void swap(const SwapMayThrow<canThrow>&, const SwapMayThrow<canThrow>&) noexcept(!canThrow);34 35static_assert(ConstMemberSwapNoexcept<std::pair<SwapMayThrow<false>, SwapMayThrow<false>>>);36static_assert(!ConstMemberSwapNoexcept<std::pair<SwapMayThrow<true>, SwapMayThrow<false>>>);37static_assert(!ConstMemberSwapNoexcept<std::pair<SwapMayThrow<false>, SwapMayThrow<true>>>);38static_assert(!ConstMemberSwapNoexcept<std::pair<SwapMayThrow<true>, SwapMayThrow<true>>>);39 40struct ConstSwappable {41 mutable int i;42 friend constexpr void swap(const ConstSwappable& lhs, const ConstSwappable& rhs) { std::swap(lhs.i, rhs.i); }43};44 45constexpr bool test() {46 // user defined const swap47 {48 using P = std::pair<const ConstSwappable, const ConstSwappable>;49 const P p1(ConstSwappable{0}, ConstSwappable{1});50 const P p2(ConstSwappable{2}, ConstSwappable{3});51 p1.swap(p2);52 assert(p1.first.i == 2);53 assert(p1.second.i == 3);54 assert(p2.first.i == 0);55 assert(p2.second.i == 1);56 }57 58 // pair of references59 {60 int i1 = 0, i2 = 1, i3 = 2, i4 = 3;61 const std::pair<int&, int&> p1{i1, i2};62 const std::pair<int&, int&> p2{i3, i4};63 p1.swap(p2);64 assert(p1.first == 2);65 assert(p1.second == 3);66 assert(p2.first == 0);67 assert(p2.second == 1);68 }69 return true;70}71 72int main(int, char**) {73 test();74 75// gcc cannot have mutable member in constant expression76#if !defined(TEST_COMPILER_GCC)77 static_assert(test());78#endif79 80 return 0;81}