kblib 0.2.3
General utilities library for modern C++
variant.cpp
Go to the documentation of this file.
1#include "catch.hpp"
2#include <chrono>
3#include <iostream>
4#include <map>
5#include <string_view>
6
7#include "kblib/variant.h"
8
9#include "kblib/hash.h"
10
11#if KBLIB_USE_CXX17
12
13TEST_CASE("visit") {
14 std::variant<std::monostate, int, std::string> var = 10;
15
16 // standard syntax (with visitor helper):
17 std::visit(kblib::visitor{[](std::monostate) { REQUIRE(false); },
18 [](int) { REQUIRE(true); },
19 [](const std::string&) { REQUIRE(false); }},
20 var);
21
22 // Basic single-variant syntax:
24 var, [](std::monostate) { REQUIRE(false); }, [](int) { REQUIRE(true); },
25 [](const std::string&) { REQUIRE(false); });
26
27 // Pattern-matching-like syntax:
28 kblib::visit(var)([](std::monostate) { REQUIRE(false); },
29 [](int) { REQUIRE(true); },
30 [](const std::string&) { REQUIRE(false); });
31
32 // kblib::visit2(var, [](int) {});
33}
34
35TEST_CASE("visit2") {
36 std::variant<std::monostate, int, std::string> var = 10;
37
38 // standard syntax (with visitor helper):
39 std::visit(kblib::visitor{[](std::monostate) { REQUIRE(false); },
40 [](int) { REQUIRE(true); },
41 [](const std::string&) { REQUIRE(false); }},
42 var);
43
44 // Basic single-variant syntax:
46 var, [](std::monostate) { REQUIRE(false); }, [](int) { REQUIRE(true); },
47 [](const std::string&) { REQUIRE(false); });
48}
49
50TEST_CASE("visit_indexed") {
51 std::variant<std::monostate, int, std::string> var(std::in_place_type<int>,
52 10);
53 kblib::visit_indexed(var, [](auto constant, auto val) {
54 REQUIRE(constant == 1);
55 static_assert(
56 std::is_same_v<decltype(val),
57 std::variant_alternative_t<constant, decltype(var)>>);
58 });
59}
60
61TEST_CASE("variant_cast") {
62 std::variant<int, std::string> from(std::in_place_type<int>, 10);
63 auto to
64 = kblib::variant_cast<std::variant<std::monostate, int, std::string>>(
65 from);
66 REQUIRE(to.index() == 1);
67}
68
69#endif
Provides generic facilities for hashing data, and aliases for standard unordered containers using the...
constexpr auto visit_indexed(Variant &&variant, Fs &&... fs) -> decltype(auto)
Visit a variant, but pass the index (as an integral_constant) to the visitor. This allows for a visit...
Definition: variant.h:176
constexpr auto visit2(V &&v, F &&f, Fs &&... fs) -> decltype(auto)
Definition: variant.h:295
constexpr auto visit(V &&v, F &&f, Fs &&... fs) -> decltype(auto)
Wraps std::visit to provide an interface taking one variant and any number of functors providing an o...
Definition: variant.h:221
Helper class for std::visiting a std::variant.
Definition: variant.h:102
TEST_CASE("visit")
Definition: variant.cpp:13
Provides utilities for working with std::variant more expressively and more efficiently.