aboutsummaryrefslogtreecommitdiff
path: root/src/variant.hpp
blob: 8a5fb0324698e0ea91995e766847630b074a4b6f (plain)
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
#ifndef WANDA_VARIANT_HPP
#define WANDA_VARIANT_HPP

#include <gio/gio.h>

#include <optional>
#include <string>
#include <type_traits>

namespace wanda {

struct variant {

    explicit variant(GVariant * variant);

    ~variant();

    template<typename Type> std::optional<Type> get() const {
        if(!m_value) {
            return std::nullopt;
        }

        if constexpr(std::is_same_v<Type, bool>) {
            if(is_of_type(G_VARIANT_TYPE_BOOLEAN)) {
                return static_cast<bool>(g_variant_get_boolean(m_value));
            }
        } else if constexpr(std::is_same_v<Type, std::string>) {
            if(is_of_type(G_VARIANT_TYPE_STRING)) {
                auto length = gsize{};
                auto value = g_variant_get_string(m_value, &length);
                return std::string(value, static_cast<std::size_t>(length));
            }
        }

        return std::nullopt;
    }


private:
    bool is_of_type(GVariantType const * const type) const;

    GVariant * const m_value;
};

}

#endif