Debian Codegraph @

tests/src/utility/test_Overloaded.cpp

raw
1 #include <pbcopper/utility/Overloaded.h>
2
3 #include <pbcopper/utility/Ssize.h>
4
5 #include <gtest/gtest.h>
6
7 #include <sstream>
8 #include <string>
9 #include <variant>
10 #include <vector>
11
12 using namespace PacBio;
13
14 // clang-format off
15 TEST(Utility_Overloaded, can_overload_operations_on_variant_subtypes)
16 {
17 struct Foo{ const int Value = 42; };
18 struct Bar{ const int Value = 5; };
19 using V = std::variant<int, double, std::string, Foo, Bar>;
20
21 const std::vector<V> variants {
22 0, "pi", Bar{}, 3.14, Foo{}
23 };
24
25 std::ostringstream out;
26 for (const auto& v : variants) {
27 std::visit(Utility::Overloaded{
28 [&](const int x) { out << "int:" << x; },
29 [&](const double d) { out << "double:" << d; },
30 [&](const std::string& s) { out << "string:" << s; },
31 [&](const auto& x) { out << "default:" << x.Value; }
32 }, v);
33 out << ", ";
34 }
35 const std::string expected{
36 "int:0, string:pi, default:5, double:3.14, default:42, "
37 };
38 EXPECT_EQ(out.str(), expected);
39
40 int count = 0;
41 for (const auto& v : variants) {
42 count += std::visit(Utility::Overloaded{
43 [](const int x) { return x; },
44 [](const double d) -> int { return d; },
45 [](const std::string& s) -> int { return Utility::Ssize(s); },
46 [](const auto& x) { return x.Value; }
47 }, v);
48 }
49 EXPECT_EQ(count, 52); // 0 + 2 + 5 + 3 + 42
50 }
51 // clang-format on