Skip to content

Instantly share code, notes, and snippets.

@iKlsR
Forked from alexesDev/main.cpp
Created May 2, 2019 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iKlsR/6d4265b5ebb5f152b9d4f8111f9ff27e to your computer and use it in GitHub Desktop.
Save iKlsR/6d4265b5ebb5f152b9d4f8111f9ff27e to your computer and use it in GitHub Desktop.
Redux c++ implementation
#include <mapbox/variant.hpp>
#include <redux.hpp>
struct Increment
{
};
struct Decrement
{
};
typedef mapbox::util::variant<
Increment,
Decrement
> Action;
struct State {
int value = 0;
};
struct Reducer {
const State &currentState;
State operator()(const Increment &) {
return State { currentState.value + 1 };
}
State operator()(const Decrement &) {
return State { currentState.value - 1 };
}
};
typedef Redux::Store<Action, State, Reducer> Store;
int main() {
Store store;
store.dispatch(Increment());
store.dispatch(Decrement());
store.dispatch(Increment());
store.dispatch(Increment());
std::cout << store.getState().value << std::endl;
}
#pragma once
#include <mapbox/variant.hpp>
#include <functional>
#include <vector>
namespace Redux {
template<typename Action, typename State, typename Reducer>
struct Store
{
void dispatch(const Action &action) {
mState = mapbox::util::apply_visitor(Reducer{ mState }, action);
for(const auto &listener : mListeners) {
listener();
}
}
const State &getState() const {
return mState;
}
std::function<void()> subscribe(std::function<void()> listener) {
int index = mListeners.size();
mListeners.push_back(listener);
return [index, this]() {
mListeners.erase(mListeners.begin() + index);
};
}
private:
std::vector<std::function<void()>> mListeners;
State mState;
};
}
// https://github.com/mapbox/variant
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment