Created
June 3, 2020 02:34
-
-
Save OmarElawady/acff8fe7b2ac9b3fbb83e2acb2dc4d2e to your computer and use it in GitHub Desktop.
A design pattern (?) to simplifit checkpointing and rollbacking assignments. Can be useful when implementing backtracking.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <bits/stdc++.h> | |
| using namespace std; | |
| template <class T> | |
| class TimeMachine{ | |
| private: | |
| class Wrapper{ | |
| private: | |
| TimeMachine& tm; | |
| T& item; | |
| public: | |
| Wrapper(TimeMachine& tm, T& item) : tm{tm}, item{item} { | |
| } | |
| T& operator=(T lv){ | |
| tm.mods.emplace_back(&item, item); | |
| item = lv; | |
| } | |
| }; | |
| vector<pair<T*, T>> mods; | |
| vector<int> check_points; | |
| public: | |
| void checkpoint(){ | |
| check_points.push_back(mods.size()); | |
| } | |
| Wrapper operator()(T& item){ | |
| return Wrapper(*this, item); | |
| } | |
| void rollback(){ | |
| while(mods.size() != check_points.back()){ | |
| T* item = mods.back().first; | |
| T oldval = mods.back().second; | |
| *item = oldval; | |
| mods.pop_back(); | |
| } | |
| check_points.pop_back(); | |
| } | |
| }; | |
| void print_triplets(int a, int b, int c, string msg){ | |
| cout << msg << endl << "a: " << a << ", b = " << b << ",c = " << c << endl; | |
| } | |
| int main(){ | |
| TimeMachine<int> T; | |
| int a, b, c; | |
| a = b = c = 10; | |
| print_triplets(a, b, c, "Before first checkpoint"); | |
| T.checkpoint(); | |
| T(a) = 1; | |
| T(b) = 2; | |
| T(c) = 3; | |
| print_triplets(a, b, c, "Before second checkpoint"); | |
| T.checkpoint(); | |
| T(a) = 4; | |
| T(c) = 5; | |
| print_triplets(a, b, c, "Latest value"); | |
| T.rollback(); | |
| print_triplets(a, b, c, "After First rollback"); | |
| T.rollback(); | |
| print_triplets(a, b, c, "After second rollback"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment