Created
July 10, 2018 13:49
-
-
Save MarioLiebisch/514fa963f67400abd20250fb26e07228 to your computer and use it in GitHub Desktop.
Simple implementation of an observable variable that will trigger once its value is changed (and which could be adjusted in the callback). This was really just a random idea, it's not perfect by any means.
This file contains 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 <iostream> | |
#include <functional> | |
#include <string> | |
// Definee an `Observable` class. | |
// This works as a wrapper around a variable of any type. | |
// Once it's assigned a new value, a predefined callback is defined to react on this. | |
template<typename T> | |
class Observable { | |
public: | |
// Define the callback function's signature/type | |
typedef std::function<const T(const std::string&, const T&, const T&)> cbfunc; | |
private: | |
const std::string mName; // Optional name of this variable | |
T mValue; // Wrapped variable/value | |
const cbfunc mCallback; // Callback for changes | |
public: | |
// Constructor | |
Observable(cbfunc callback, const std::string &name = "") : mName(name), mCallback(callback) {} | |
// Constructor with predefined value | |
Observable(const T &value, cbfunc callback, const std::string &name = "") : mName(name), mValue(value), mCallback(callback) {} | |
// Assignment operator | |
Observable &operator=(const T &value) { | |
const T prev = mValue; // Save the previous value | |
mValue = mCallback(mName, prev, value); // Run our callback to determine the new value | |
return *this; // return this object by reference | |
} | |
// Simple conversion operator | |
operator T() { return mValue; } | |
}; | |
int main(int argc, char **argv) { | |
Observable<int> myNumber([](const std::string &name, const int &prev, const int &next) { | |
// Print a message | |
std::cout << name << " has changed from " << prev << " to " << next << ".\n"; | |
// Return the new value (we could also modify this, e.g. to limit changes.) | |
return next; | |
}, "myNumber"); | |
myNumber = 123; | |
myNumber = 543; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment