From edf20947014c2a3f044858ec75a7f953f5c41175 Mon Sep 17 00:00:00 2001 From: nihonium Date: Thu, 3 Nov 2022 15:05:26 +0300 Subject: [PATCH 1/2] seminar 04 07_manager --- seminar04_templates/07_manager/main.cpp | 42 +++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 seminar04_templates/07_manager/main.cpp diff --git a/seminar04_templates/07_manager/main.cpp b/seminar04_templates/07_manager/main.cpp new file mode 100644 index 0000000..870865b --- /dev/null +++ b/seminar04_templates/07_manager/main.cpp @@ -0,0 +1,42 @@ +#include +#include + +template +class Manager { +private: + T* mPtr; +public: + Manager() { + mPtr = nullptr; + } + void allocate() { + mPtr = (T*)malloc(sizeof(T)); + } + void construct(const T& t) { + new(mPtr) T{t}; + } + T& get() { + return *mPtr; + } + void destruct() { + mPtr->~T(); + } + void deallocate() { + free(mPtr); + } +}; + +int main() { + Manager a; + a.allocate(); + a.construct("Cats and dogs"); + a.get() += " and elephants"; + std::cout << a.get() << std::endl; + a.destruct(); + + a.construct("Sapere aude"); + std::cout << a.get() << std::endl; + + a.destruct(); + a.deallocate(); +} From 094a022df86231db951c779d1103f3d591c80049 Mon Sep 17 00:00:00 2001 From: nihonium Date: Thu, 3 Nov 2022 20:37:50 +0300 Subject: [PATCH 2/2] finished seminar04 --- seminar04_templates/08_ref/main.cpp | 74 +++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 seminar04_templates/08_ref/main.cpp diff --git a/seminar04_templates/08_ref/main.cpp b/seminar04_templates/08_ref/main.cpp new file mode 100644 index 0000000..1f9f0f9 --- /dev/null +++ b/seminar04_templates/08_ref/main.cpp @@ -0,0 +1,74 @@ +#include +#include +#include + +using std::cout, std::endl, std::string, std::vector; + +template +class Ref { +private: + T* mPtr; +public: + Ref(T& t) { + mPtr = &t; + } + Ref(Ref& t) { + mPtr = t.mPtr; + } + Ref() { + mPtr = nullptr; + } + T& get() { + return *mPtr; + } + T operator=(const T& t) { + new(mPtr) T{t}; + return *mPtr; + } + T operator+(const T& t) { + return *mPtr + t; + } + T operator+=(const T& t) { + *mPtr = *mPtr + t; + return *mPtr; + } + T* operator->() { + return mPtr; + } + template + friend std::ostream& operator<<(std::ostream& out, Ref r); +}; + +template +std::ostream& operator<<(std::ostream& out, Ref r) { + out << *(r.mPtr); + return out; +} + +void toUpper(Ref r) { + for(size_t i = 0; i < r->size(); ++i) + r.get()[i] = toupper(r.get()[i]); +} + +int main() { + int a = 10; + Ref ra = a; + cout << ra << endl; + + string s = "Cat"; + Ref rs = s; + rs = "Mouse"; + rs += "Elephant"; + cout << rs << endl; + cout << s << endl; + + toUpper(s); + cout << s << endl; + + vector animals {"Cat", "Dogs", "Elephants", "Worms"}; + vector> refs {animals.begin(), animals.end()}; + + for (int i = 0; i < refs.size(); ++i) + cout << animals[i] << " "; + cout << endl; +}