LoginSignup
0
0

More than 1 year has passed since last update.

C++ で Solid.JS ぽいことをする遊び

Posted at

Solid.JS の仕組みの説明を読んでいたら面白そうだったので、C++ で実装してみる遊びです。

スレッド安全とか難しいことは無視しています。

たったこれだけでリアクティブ遊びができるのは面白いですね。

コード

#include <string>
#include <iostream>
#include <functional>
#include <optional>
#include <vector>

using Subscriber = std::function<void()>;
static std::optional<Subscriber> subscriberContext;

template <typename T>
class Signal {
	T v;
	std::vector<Subscriber> subscribers;
public:
	Signal(T initial) : v(initial), subscribers() {}
	T get() {
		if (subscriberContext) {
			subscribers.push_back(subscriberContext.value());
		}
		return v;
	}
	void set(T const& v) {
		this->v = v;
		for (auto&& each : subscribers) {
			each();
		}
	}
};

class Effect {
public:
	Effect(std::function<void()> on_mount) {
		subscriberContext = on_mount;
		on_mount();
		subscriberContext = std::nullopt;
	}
};

int main() {
	Signal<std::string> s("Hello");
	Effect e([&]() {
		auto a = s.get();
		std::cout << a << std::endl;
	});
	s.set("World!");
}

実行結果

Hello
World!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0