result.hpp 1.32 KB
Newer Older
1
2
3
4
5
6
7
#ifndef __INFINIUTILS_RESULT_H__
#define __INFINIUTILS_RESULT_H__

#include "check.h"
#include <infinicore.h>
#include <variant>

8
9
10
11
12
#define CHECK_RESULT(RESULT)    \
    if (!RESULT) {              \
        return RESULT.status(); \
    }

13
14
15
16
17
18
19
20
namespace utils {

template <typename T, typename = std::enable_if_t<!std::is_same_v<T, infiniStatus_t>>>
class Result {
    std::variant<infiniStatus_t, T> _result;

public:
    explicit Result(T value) : _result(std::move(value)) {}
21
    Result(infiniStatus_t status) : _result(status) {
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
        if (status == INFINI_STATUS_SUCCESS) {
            std::cerr << "Warning: Result created with success status but value is not set." << std::endl;
            std::abort();
        }
    }

    infiniStatus_t status() const {
        return _result.index() == 0 ? std::get<0>(_result) : INFINI_STATUS_SUCCESS;
    }

    T take() {
        return std::move(std::get<1>(_result));
    }

    operator bool() const {
        return status() == INFINI_STATUS_SUCCESS;
    }

    T *operator->() {
        return &std::get<1>(_result);
    }

    const T *operator->() const {
        return &std::get<1>(_result);
    }

    T &operator*() {
        return std::get<1>(_result);
    }

    const T &operator*() const {
        return std::get<1>(_result);
    }
};

} // namespace utils

#endif // __INFINIUTILS_RESULT_H__