aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/memory/function_view-inl.h
blob: ececfdf3357e98fe3854600244176bbbf17dd58e (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
#pragma once
#ifndef FUNCTION_VIEW_INL_H_
#error "Direct inclusion of this file is not allowed, include function_view.h"
// For the sake of sane code completion.
#include "function_view.h"
#endif

#include <library/cpp/yt/assert/assert.h>

namespace NYT {

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

template <class TResult, bool NoExcept, class... TArgs>
template <CTypeErasable<TResult(TArgs...) noexcept(NoExcept)> TConcrete>
TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::TFunctionView(TConcrete& concreteRef) noexcept
    : TFunctionView(&concreteRef)
{ }

template <class TResult, bool NoExcept, class... TArgs>
template <CTypeErasable<TResult(TArgs...) noexcept(NoExcept)> TConcrete>
TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::TFunctionView(TConcrete* concretePtr) noexcept
{
    Ptr_ = reinterpret_cast<void*>(concretePtr);
    Invoke_ = &TFunctionView::ConcreteInvoke<TConcrete>;
}

template <class TResult, bool NoExcept, class... TArgs>
TFunctionView<TResult(TArgs...) noexcept(NoExcept)>
TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::Release() noexcept
{
    auto copy = *this;
    Reset();
    return copy;
}

template <class TResult, bool NoExcept, class... TArgs>
TResult TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::operator()(TArgs... args) noexcept(NoExcept)
{
    YT_VERIFY(Ptr_);
    return Invoke_(std::forward<TArgs>(args)..., Ptr_);
}

template <class TResult, bool NoExcept, class... TArgs>
template <class TConcrete>
TResult TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::ConcreteInvoke(TArgs... args, TErasedPtr ptr) noexcept(NoExcept)
{
    return (*reinterpret_cast<TConcrete*>(ptr))(std::forward<TArgs>(args)...);
}

template <class TResult, bool NoExcept, class... TArgs>
TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::operator bool() const noexcept
{
    return IsValid();
}

template <class TResult, bool NoExcept, class... TArgs>
bool TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::IsValid() const noexcept
{
    return Ptr_ != nullptr;
}

template <class TResult, bool NoExcept, class... TArgs>
void TFunctionView<TResult(TArgs...) noexcept(NoExcept)>::Reset() noexcept
{
    Ptr_ = nullptr;
}

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

} // namespace NYT