aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/misc/strong_typedef.h
blob: 58d96ebd2cfec314b94badb4f62863a755f8b98d (plain) (blame)
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
#pragma once

#include <utility>

#include <util/generic/string.h>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

template <class T, class TTag>
class TStrongTypedef
{
public:
    using TUnderlying = T;

    constexpr TStrongTypedef()
        requires std::is_default_constructible_v<T>;

    constexpr explicit TStrongTypedef(const T& underlying)
        requires std::is_copy_constructible_v<T>;

    constexpr explicit TStrongTypedef(T&& underlying)
        requires std::is_move_constructible_v<T>;

    TStrongTypedef(const TStrongTypedef&) = default;
    TStrongTypedef(TStrongTypedef&&) = default;

    TStrongTypedef& operator=(const TStrongTypedef&) = default;
    TStrongTypedef& operator=(TStrongTypedef&&) = default;

    constexpr explicit operator const T&() const;
    constexpr explicit operator T&();

    #define XX(op) \
        constexpr auto operator op(const TStrongTypedef& rhs) const \
            noexcept(noexcept(Underlying_ op rhs.Underlying_)) \
                requires requires(T lhs, T rhs) {lhs op rhs; };

    XX(<)
    XX(>)
    XX(<=)
    XX(>=)
    XX(==)
    XX(!=)
    XX(<=>)

    #undef XX

    explicit operator bool() const
        noexcept(noexcept(static_cast<bool>(Underlying_)));

    constexpr T& Underlying() &;
    constexpr const T& Underlying() const &;
    constexpr T&& Underlying() &&;

private:
    T Underlying_;
};

#define YT_DEFINE_STRONG_TYPEDEF(T, TUnderlying) \
    struct T ## Tag \
    { }; \
    using T = ::NYT::TStrongTypedef<TUnderlying, T##Tag>; \

template <class T>
struct TStrongTypedefTraits;

template <class T>
concept CStrongTypedef = TStrongTypedefTraits<T>::IsStrongTypedef;

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT

#define STRONG_TYPEDEF_INL_H_
#include "strong_typedef-inl.h"
#undef STRONG_TYPEDEF_INL_H_