-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy path234.md
106 lines (82 loc) · 2.31 KB
/
234.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<details open><summary>Info</summary><p>
* **Did you know about function-try-block and that exceptions caught inside that block are implicitly rethrown?**
* http://eel.is/c++draft/except.pre#nt:function-try-block
</p></details><details open><summary>Example</summary><p>
```cpp
struct foo {
foo() { throw 0; }
};
struct bar {
bar() try : foo_{} {
// constructor body
}
catch (...)
{
// exceptions from the initializer list are caught here
// but also re-thrown after this block (unless the program is aborted)
}
private:
foo foo_;
};
int main() try {
bar b{};
}
catch(...) {
// okay, exception cought here!
}
```
> https://godbolt.org/z/Y4efK573f
</p></details><details open><summary>Puzzle</summary><p>
* **Can you implement `foo`'s constructor which initializes `Ts...` and sets `exception` to true if any exception is thrown and rethrows it?**
```cpp
template<class TException>
struct ctor_except {
ctor_except() { throw TException{}; }
};
template<class... Ts>
struct foo : Ts... {
explicit(true) foo(bool& exception); // TODO
};
int main() {
using namespace boost::ut;
"function-try-block"_test = [] {
bool exception{false};
struct bar { };
should("not set exception with empty list") = [=] {
expect(nothrow([&]{ foo<>{mut(exception)}; }) and not exception);
};
should("not set exception with non-throwing types") = [=] {
expect(nothrow([&]{ foo<bar>{mut(exception)}; }) and not exception);
};
should("catch exception if thrown from within the constructor") = [=] {
expect(throws<int>([&]{ foo<ctor_except<int>>{mut(exception)}; }) and exception);
};
should("catch exception if thrown from within the constructor with muliple types") = [=] {
expect(throws<int>([&]{ foo<bar, ctor_except<int>>{mut(exception)}; }) and exception);
};
};
}
```
> https://godbolt.org/z/s3MzE8xM9
</p></details><details><summary>Solutions</summary><p>
```cpp
template<class... Ts>
struct foo : Ts... {
explicit(true) foo (bool& exception) try : Ts{}... {
} catch (...) {
exception = true;
}
};
```
> https://godbolt.org/z/8Yxr7WbsM
```cpp
template<class... Ts>
struct foo : Ts... {
explicit(true) foo(bool& exception) try : Ts()... {
exception = false;
} catch(...) {
exception = true;
}
};
```
> https://godbolt.org/z/dnhcjsYjK