Skip to content

Instantly share code, notes, and snippets.

@Nexuapex Nexuapex/inlined.h
Last active Aug 29, 2015

Embed
What would you like to do?
I would get behind this if I could just static_assert(size <= Size) in the placement operator new. Close but no cigar.
#ifndef INLINED_OBJECT_H
#define INLINED_OBJECT_H
#include <string.h>
template <typename T, size_t Size>
class inlined
{
public:
inlined();
inlined(inlined const&);
inlined& operator=(inlined const&);
T& operator*() { return reinterpret_cast<T&>(*buffer); }
T const& operator*() const { return reinterpret_cast<T const&>(*buffer); }
T* operator->() { return reinterpret_cast<T*>(buffer); }
T const* operator->() const { return reinterpret_cast<T const*>(buffer); }
operator T*() { return reinterpret_cast<T*>(buffer); }
operator T const*() const { return reinterpret_cast<T const*>(buffer); }
private:
char buffer[Size];
#ifdef INLINED_DEBUG_REFERENCE
T& object;
#endif
};
template <typename T, size_t Size>
void* operator new(size_t, inlined<T, Size>& place)
{
return place;
}
template <typename T, size_t Size>
void operator delete(void*, inlined<T, Size>&)
{
}
template <typename T, size_t Size>
inlined<T, Size>::inlined()
#ifdef INLINED_DEBUG_REFERENCE
: object(reinterpret_cast<T&>(*buffer))
#endif
{
#ifdef INLINED_DEBUG_MEMSET
memset(buffer, INLINED_DEBUG_MEMSET, Size);
#endif
}
template <typename T, size_t Size>
inlined<T, Size>::inlined(inlined const& rhs)
#ifdef INLINED_DEBUG_REFERENCE
: object(reinterpret_cast<T&>(*buffer))
#endif
{
memmove(buffer, rhs.buffer, Size);
}
template <typename T, size_t Size>
inlined<T, Size>& inlined<T, Size>::operator=(inlined const& rhs)
{
memcpy(buffer, rhs.buffer, Size);
return *this;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.