7#ifndef DUNE_FUNCTIONS_COMMON_POLYMORPHICSMALLOBJECT_HH
8#define DUNE_FUNCTIONS_COMMON_POLYMORPHICSMALLOBJECT_HH
49template<
class Base,
size_t bufferSize>
53 static constexpr std::size_t actualBufferSize = std::max(
sizeof(std::byte), bufferSize);
57 static constexpr std::size_t bufferAlignment =
alignof(std::max_align_t);
72 template<
class Derived,
73 std::enable_if_t<std::is_base_of_v<Base, std::remove_cv_t<
74 std::remove_reference_t<Derived>>>,
int> = 0>
77 constexpr bool useBuffer = (
sizeof(Derived) <= bufferSize)
78 && (bufferAlignment %
alignof(Derived) == 0);
80 if constexpr (useBuffer) {
81 p_ =
new (&buffer_) Derived(std::forward<Derived>(derived));
83 p_ =
new Derived(std::forward<Derived>(derived));
90 moveToWrappedObject(std::move(other));
96 copyToWrappedObject(other);
102 destroyWrappedObject();
110 destroyWrappedObject();
111 copyToWrappedObject(other);
119 destroyWrappedObject();
120 moveToWrappedObject(std::move(other));
125 explicit operator bool()
const
133 return ((
void*) (p_) == (
void*)(&buffer_));
150 void destroyWrappedObject() noexcept
163 if (other.bufferUsed())
164 p_ = other.p_->move(&buffer_);
182 if (other.bufferUsed())
183 p_ = other.p_->clone(&buffer_);
185 p_ = other.p_->clone();
188 alignas(bufferAlignment) std::byte buffer_[actualBufferSize];
Definition polynomial.hh:17
A wrapper providing small object optimization with polymorphic types.
Definition polymorphicsmallobject.hh:51
const Base & get() const
Obtain reference to stored object.
Definition polymorphicsmallobject.hh:137
bool bufferUsed() const
Check if object is stored in internal stack buffer.
Definition polymorphicsmallobject.hh:131
PolymorphicSmallObject(Derived &&derived)
Construct from object.
Definition polymorphicsmallobject.hh:75
PolymorphicSmallObject(PolymorphicSmallObject &&other) noexcept
Move constructor from other PolymorphicSmallObject.
Definition polymorphicsmallobject.hh:88
PolymorphicSmallObject & operator=(const PolymorphicSmallObject &other)
Copy assignment from other PolymorphicSmallObject.
Definition polymorphicsmallobject.hh:106
PolymorphicSmallObject & operator=(PolymorphicSmallObject &&other) noexcept
Move assignment from other PolymorphicSmallObject.
Definition polymorphicsmallobject.hh:117
PolymorphicSmallObject(const PolymorphicSmallObject &other)
Copy constructor from other PolymorphicSmallObject.
Definition polymorphicsmallobject.hh:94
~PolymorphicSmallObject()
Destructor.
Definition polymorphicsmallobject.hh:100
PolymorphicSmallObject()
Default constructor.
Definition polymorphicsmallobject.hh:62
Base & get()
Obtain mutable reference to stored object.
Definition polymorphicsmallobject.hh:143