functional.hpp 1.64 KB
Newer Older
1
2
3
#ifndef CK_FUNCTIONAL_HPP
#define CK_FUNCTIONAL_HPP

Chao Liu's avatar
Chao Liu committed
4
5
#include "integral_constant.hpp"
#include "Sequence.hpp"
6

7
8
namespace ck {

Chao Liu's avatar
Chao Liu committed
9
10
11
struct forwarder
{
    template <typename T>
Chao Liu's avatar
Chao Liu committed
12
    __host__ __device__ constexpr T&& operator()(T&& x) const
Chao Liu's avatar
Chao Liu committed
13
    {
Chao Liu's avatar
Chao Liu committed
14
        return static_cast<T&&>(x);
Chao Liu's avatar
Chao Liu committed
15
16
17
    }
};

Chao Liu's avatar
Chao Liu committed
18
19
20
21
22
23
24
25
struct swallow
{
    template <class... Ts>
    __host__ __device__ constexpr swallow(Ts&&... ts)
    {
    }
};

Chao Liu's avatar
Chao Liu committed
26
// Emulate if constexpr
Chao Liu's avatar
Chao Liu committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
template <bool Predicate>
struct static_if
{
};

template <>
struct static_if<true>
{
    using Type = static_if<true>;

    template <class F>
    __host__ __device__ constexpr auto operator()(F f) const
    {
        // This is a trick for compiler:
Chao Liu's avatar
Chao Liu committed
41
        //   Pass forwarder to lambda "f" as "auto" argument, and make sure "f" will use it,
Chao Liu's avatar
Chao Liu committed
42
43
        //   this will make "f" a generic lambda, so that "f" won't be compiled until being
        //   instantiated here
Chao Liu's avatar
Chao Liu committed
44
45
46
47
48
        f(forwarder{});
        return Type{};
    }

    template <class F>
49
    __host__ __device__ static constexpr auto Else(F)
Chao Liu's avatar
Chao Liu committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    {
        return Type{};
    }
};

template <>
struct static_if<false>
{
    using Type = static_if<false>;

    template <class F>
    __host__ __device__ constexpr auto operator()(F) const
    {
        return Type{};
    }

    template <class F>
67
    __host__ __device__ static constexpr auto Else(F f)
Chao Liu's avatar
Chao Liu committed
68
69
    {
        // This is a trick for compiler:
Chao Liu's avatar
Chao Liu committed
70
        //   Pass forwarder to lambda "f" as "auto" argument, and make sure "f" will use it,
Chao Liu's avatar
Chao Liu committed
71
72
        //   this will make "f" a generic lambda, so that "f" won't be compiled until being
        //   instantiated here
Chao Liu's avatar
Chao Liu committed
73
74
75
76
        f(forwarder{});
        return Type{};
    }
};
77
78
79

} // namespace ck
#endif