Skip to content

Commit 3f58e56

Browse files
authored
Update 001_utility_exchange.cpp
1 parent ed2ec89 commit 3f58e56

1 file changed

Lines changed: 53 additions & 1 deletion

File tree

cpp_14/001_utility_exchange.cpp

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
1-
1
1+
#include <iostream>
2+
#include <utility>
3+
#include <vector>
4+
#include <iterator>
5+
6+
class stream
7+
{
8+
public:
9+
10+
using flags_type = int;
11+
12+
public:
13+
14+
flags_type flags() const
15+
{ return flags_; }
16+
17+
/// 以 newf 替换 flags_ 并返回旧值。
18+
flags_type flags(flags_type newf)
19+
{ return std::exchange(flags_, newf); }
20+
21+
private:
22+
23+
flags_type flags_ = 0;
24+
};
25+
26+
void f() { std::cout << "f()"; }
27+
28+
int main()
29+
{
30+
stream s;
31+
32+
std::cout << s.flags() << '\n';
33+
std::cout << s.flags(12) << '\n';
34+
std::cout << s.flags() << "\n\n";
35+
36+
std::vector<int> v;
37+
38+
// 因为第二模板形参有默认值,故能以花括号初始化列器表为第二参数。
39+
// 下方表达式等价于 std::exchange(v, std::vector<int>{1,2,3,4});
40+
41+
std::exchange(v, {1,2,3,4});
42+
43+
std::copy(begin(v),end(v), std::ostream_iterator<int>(std::cout,", "));
44+
45+
std::cout << "\n\n";
46+
47+
void (*fun)();
48+
49+
// 模板形参的默认值亦使得能以通常函数为第二参数。
50+
// 下方表达式等价于 std::exchange(fun, static_cast<void(*)()>(f))
51+
std::exchange(fun,f);
52+
fun();
53+
}

0 commit comments

Comments
 (0)