1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // UNSUPPORTED: c++98, c++03, c++11 11 // <utility> 12 13 // exchange 14 15 // template<class T, class U=T> 16 // constexpr T // constexpr after C++17 17 // exchange(T& obj, U&& new_value); 18 19 #include <utility> 20 #include <cassert> 21 #include <string> 22 23 #include "test_macros.h" 24 25 #if TEST_STD_VER > 17 26 TEST_CONSTEXPR bool test_constexpr() { 27 int v = 12; 28 29 if (12 != std::exchange(v,23) || v != 23) 30 return false; 31 32 if (23 != std::exchange(v,static_cast<short>(67)) || v != 67) 33 return false; 34 35 if (67 != std::exchange<int, short>(v, {}) || v != 0) 36 return false; 37 return true; 38 } 39 #endif 40 41 42 43 int main() 44 { 45 { 46 int v = 12; 47 assert ( std::exchange ( v, 23 ) == 12 ); 48 assert ( v == 23 ); 49 assert ( std::exchange ( v, static_cast<short>(67) ) == 23 ); 50 assert ( v == 67 ); 51 52 assert ((std::exchange<int, short> ( v, {} )) == 67 ); 53 assert ( v == 0 ); 54 55 } 56 57 { 58 bool b = false; 59 assert ( !std::exchange ( b, true )); 60 assert ( b ); 61 } 62 63 { 64 const std::string s1 ( "Hi Mom!" ); 65 const std::string s2 ( "Yo Dad!" ); 66 std::string s3 = s1; // Mom 67 assert ( std::exchange ( s3, s2 ) == s1 ); 68 assert ( s3 == s2 ); 69 assert ( std::exchange ( s3, "Hi Mom!" ) == s2 ); 70 assert ( s3 == s1 ); 71 72 s3 = s2; // Dad 73 assert ( std::exchange ( s3, {} ) == s2 ); 74 assert ( s3.size () == 0 ); 75 76 s3 = s2; // Dad 77 assert ( std::exchange ( s3, "" ) == s2 ); 78 assert ( s3.size () == 0 ); 79 } 80 81 #if TEST_STD_VER > 17 82 static_assert(test_constexpr()); 83 #endif 84 } 85