Skip to content

Instantly share code, notes, and snippets.

@kspalaiologos
Created June 28, 2023 20:50
Show Gist options
  • Save kspalaiologos/227873b12627dfeec382c2d21d51f94a to your computer and use it in GitHub Desktop.
Save kspalaiologos/227873b12627dfeec382c2d21d51f94a to your computer and use it in GitHub Desktop.
template<typename T>
struct artificially_constructible {
template<typename... Args>
explicit artificially_constructible(Args&&... args) {
new (&storage) T(std::forward<Args>(args)...);
}
~artificially_constructible() {
get_ptr()->~T();
}
artificially_constructible(const artificially_constructible&) {
std::abort();
}
artificially_constructible(artificially_constructible&&) {
std::abort();
}
artificially_constructible& operator=(const artificially_constructible&) {
std::abort();
}
artificially_constructible& operator=(artificially_constructible&&) {
std::abort();
}
T* get_ptr() {
return reinterpret_cast<T*>(&storage);
}
const T* get_ptr() const {
return reinterpret_cast<const T*>(&storage);
}
T* operator->() { return get_ptr(); }
const T* operator->() const { return get_ptr(); }
T& get() { return *get_ptr(); }
const T& get() const { return *get_ptr(); }
T& operator*() { return get(); }
const T& operator*() const { return get(); }
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment