Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <cstring>
- #include <memory>
- namespace eddsl {
- template<typename T>
- class optional {
- using type_value = T;
- public:
- optional() : assigne(nullptr) {
- }
- optional(const optional& cpy) : optional(*cpy.assigne) {
- }
- optional(optional&& cpy) : optional(std::move(*cpy.assigne)) {
- cpy.assigne = nullptr;
- }
- optional(const type_value & object) {
- make_copy_object(object);
- }
- optional(type_value&& object) {
- make_move_object(std::move(object));
- }
- virtual ~optional() {
- if(assigne) {
- assigne->~type_value();
- }
- }
- optional& operator=(const type_value & object) {
- make_copy_object(object);
- return *this;
- }
- optional& operator=(type_value && object) {
- make_move_object(std::move(object));
- return *this;
- }
- bool has_value() {
- return assigne != nullptr;
- }
- explicit operator bool() {
- return has_value();
- }
- type_value* operator->() {
- return assigne;
- }
- type_value & value() {
- if(assigne) return (type_value) data;
- else return nullptr;
- }
- template<typename U>
- type_value & value_or(U&& val) {
- if(assigne) {
- return *assigne;
- }
- else return val;
- }
- private:
- inline void delete_current_object() {
- if(assigne) {
- assigne->~type_value();
- }
- }
- inline void make_copy_object(const type_value& object) {
- delete_current_object();
- this->assigne = reinterpret_cast<type_value*>(&data);
- new (this->assigne) type_value (object);
- }
- inline void make_move_object(type_value&& object) {
- delete_current_object();
- this->assigne = reinterpret_cast<type_value*>(&data);
- new (this->assigne) type_value (std::move(object));
- }
- type_value * assigne = nullptr;
- uint8_t data[sizeof(T)];
- };
- } //end namespace eddie
- int i = 0;
- class tete {
- public:
- tete(int x) : x(x) {
- p = i++;
- std::cout << "BUILD " << p << std::endl;
- }
- tete(tete&& t) {
- this->x = t.x;
- t.x = -1;
- p = i++;
- }
- virtual ~tete() {
- std::cout << "Releasing" << p << " :: " << x << std::endl;
- }
- tete& operator=(const tete&) = default;
- int x;
- int p;
- };
- int main() {
- tete(12);
- {
- eddsl::optional<tete> data;
- data = tete {5};
- eddsl::optional<tete> data2(std::move(data));
- if (data) {
- std::cout << "OK" << std::endl;
- } else {
- std::cout << "NOK" << std::endl;
- }
- // auto res = data.value_or(std::move(tete(2)));
- // std::cout << res.x << std::endl;
- std::cout << "Near out of scope" << std::endl;
- }
- std::cout << "ENDING" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment