#include <functional>
#include <list>
struct MyType {
MyType(int init): mValue(init) { }
void AddHandlerOnValueChanged(std::function<bool(MyType const &, int)> handlerOnValueChanged) {
mHandlersOnValueChanged.push_back(handlerOnValueChanged);
}
void ChangeValue(int value) {
mValue = value;
NotifyValueChanged(value);
}
int GetValue(void) const {
return mValue;
}
private:
void NotifyValueChanged(int value) {
auto & handlers = mHandlersOnValueChanged; // 長いのでエイリアス
auto i = handlers.begin();
auto e = handlers.end();
while(i != e) {
if((*i)(*this, value)) {
++i;
} else { // 返り値がfalseならハンドラーを削除
i = handlers.erase(i);
}
}
}
int mValue;
std::list<std::function<bool(MyType const &, int)>> mHandlersOnValueChanged;
};
#include <iostream>
int main(void) {
MyType obj(100);
obj.AddHandlerOnValueChanged([](MyType const & o, int v) { std::cout << "!" << v << std::endl; return v % 2 == 0; });
obj.AddHandlerOnValueChanged([](MyType const & o, int v) { std::cout << "*" << v << std::endl; return v % 2 == 1; });
obj.ChangeValue(1);
obj.ChangeValue(2);
obj.ChangeValue(3);
return 0;
}
I2luY2x1ZGUgPGZ1bmN0aW9uYWw+CiNpbmNsdWRlIDxsaXN0PgoKc3RydWN0IE15VHlwZSB7CgogIE15VHlwZShpbnQgaW5pdCk6IG1WYWx1ZShpbml0KSB7IH0KCiAgdm9pZCBBZGRIYW5kbGVyT25WYWx1ZUNoYW5nZWQoc3RkOjpmdW5jdGlvbjxib29sKE15VHlwZSBjb25zdCAmLCBpbnQpPiBoYW5kbGVyT25WYWx1ZUNoYW5nZWQpIHsKICAgIG1IYW5kbGVyc09uVmFsdWVDaGFuZ2VkLnB1c2hfYmFjayhoYW5kbGVyT25WYWx1ZUNoYW5nZWQpOwogIH0KCiAgdm9pZCBDaGFuZ2VWYWx1ZShpbnQgdmFsdWUpIHsKICAgIG1WYWx1ZSA9IHZhbHVlOwogICAgTm90aWZ5VmFsdWVDaGFuZ2VkKHZhbHVlKTsKICB9CgogIGludCBHZXRWYWx1ZSh2b2lkKSBjb25zdCB7CiAgICByZX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