any_ref.hpp 1.35 KB
Newer Older
1
2
3
#pragma once

#include <py/core/any_ref_placeholder.hpp>
4
#include <py/core/type_info.hpp>
5
6
7
8
9
10

#include <any>
#include <memory>
#include <typeinfo>

namespace mln::py
11
12
13
14
15
16
17
{
  /*
  ** std::any has a dynamic allocation mechanism, hence a lack of performance.
  ** to fix this, we use the custom `any_ref` class, which is a reference to a value of `any` type
  */
  class any_ref
  {
18
19
  public:
    any_ref() = default;
20
21
    any_ref(const any_ref& other) = default;
    any_ref(any_ref&& other) noexcept = default;
22
    any_ref(std::byte* buf, Info i);
23

24
    template <typename T, class = std::enable_if_t<!std::is_same_v<any_ref, T>>>
25
26
27
28
    any_ref(T& elm)
    {
      new (&m_held) placeholder<T>(elm);
    }
29

30
31
    void*                 data();
    const std::type_info& type() const;
32

33
34
35
36
37
38
39
40
41
42
43
44
45
    template <typename T>
    T as()
    {
      placeholder_base* tmp = reinterpret_cast<placeholder_base*>(&m_held);
      if (placeholder<std::any>* ptr = dynamic_cast<placeholder<std::any>*>(tmp))
      {
        return std::any_cast<T>(*static_cast<std::any*>(ptr->m_data));
      }
      else if (placeholder<T>* ptr = dynamic_cast<placeholder<T>*>(tmp))
      {
        return *static_cast<T*>(ptr->m_data);
      }
      else
46
      {
47
        throw std::bad_cast();
48
      }
49
    }
50

51
52
  private:
    std::aligned_storage_t<sizeof(placeholder_base), alignof(placeholder_base)> m_held;
53
  };
54
} // namespace mln::py