Back to listC++
Boost-style Optional
Lv.5910@mukitaro0 playsJan 2, 2026
Boost.Optional pattern that became std::optional. Nullable value wrapper.
preview.cpp
1#include <stdexcept>2#include <type_traits>3 4struct nullopt_t {5 explicit constexpr nullopt_t(int) {}6};7inline constexpr nullopt_t nullopt{0};8 9template<typename T>10class optional {11 alignas(T) unsigned char storage_[sizeof(T)];12 bool has_value_;13 14public:15 optional() noexcept : has_value_(false) {}16 optional(nullopt_t) noexcept : has_value_(false) {}17 18 optional(const T& value) : has_value_(true) {19 new (storage_) T(value);20 }21 22 ~optional() {23 if (has_value_) reinterpret_cast<T*>(storage_)->~T();24 }25 26 bool has_value() const noexcept { return has_value_; }27 explicit operator bool() const noexcept { return has_value_; }28 29 T& value() {30 if (!has_value_) throw std::runtime_error("bad optional access");31 return *reinterpret_cast<T*>(storage_);32 }33 34 T value_or(const T& default_value) const {35 return has_value_ ? *reinterpret_cast<const T*>(storage_) : default_value;36 }37};Custom problems are not included in rankings