-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cpp
127 lines (118 loc) · 2.95 KB
/
test.cpp
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//#define OPTIONAL_UTILITY_NO_CXX14_RETURN_TYPE_DEDUCTION
#include "optional_utility.hpp"
#include <cassert>
#include <iostream>
#include <string>
namespace
{
struct _
{
template <typename F>
_(F f)
{
try {
f();
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
assert(false && "unexpected exception");
} catch (...) {
assert(false && "unexpected exception");
}
}
};
}
#define TEST(name) _ name##__LINE__ = []
TEST(value)
{
using optional_utility::value;
{
boost::optional<int> op = 42;
assert(value(op) == 42);
}
{
boost::optional<int> op = boost::none;
try {
value(op);
assert(false && "not thrown");
} catch (boost::bad_optional_access const&) {
}
}
};
TEST(value_or)
{
using optional_utility::value_or;
{
boost::optional<int> op = 42;
assert(value_or(op, 84) == 42);
}
{
boost::optional<int> op = boost::none;
assert(value_or(op, 84) == 84);
}
};
TEST(map)
{
using optional_utility::map;
{
boost::optional<int> op = 42;
boost::optional<int> op2 = op
| map([](int i) { return i * 2; });
assert(op2.get() == 84);
}
{
boost::optional<int> op = 42;
boost::optional<int> op2 = op
| map([](int i) { return i * 2; })
| map([](int i) { return i + 1; });
assert(op2.get() == 85);
}
{
boost::optional<int> op = 42;
boost::optional<std::string> op2 = op
| map([](int i) { return std::to_string(i); });
assert(op2.get() == "42");
}
};
TEST(to_optional)
{
using optional_utility::map;
using optional_utility::to_optional;
{
boost::optional<int> op = 42;
auto op2 = op
| map([](int i) { return i * 2; })
| to_optional;
static_assert(std::is_same<decltype(op2), boost::optional<int>>::value, "");
assert(op2 == 84);
}
{
boost::optional<int> op = 42;
auto temp = op
| map([](int i) { return i * 2; });
static_assert(!std::is_same<decltype(temp), boost::optional<int>>::value, "");
auto op2 = temp
| to_optional;
assert(op2 == 84);
}
};
TEST(member_function)
{
using optional_utility::map;
using namespace std::string_literals;
{
boost::optional<std::string> op = "hello"s;
boost::optional<std::string::size_type> op2 = op
| map(&std::string::length);
assert(op2.get() == 5);
}
{
boost::optional<std::string> op = "hello"s;
boost::optional<std::string> op2 = op
| map(&std::string::substr, 1, 3);
assert(op2.get() == "ell");
}
};
#include <iostream>
int main() {
std::cout << "tests finished" << std::endl;
}