From d03bc5b78d3f8daa1f6cdeb198ba2892559cde4f Mon Sep 17 00:00:00 2001 From: tqcq <99722391+tqcq@users.noreply.github.com> Date: Thu, 4 Apr 2024 00:19:20 +0000 Subject: [PATCH] fix event_bus --- src/sled/event_bus/event_bus.h | 13 +++++++++++-- src/sled/event_bus/event_bus_test.cc | 24 +++++++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/sled/event_bus/event_bus.h b/src/sled/event_bus/event_bus.h index ec8698e..48f6c9d 100644 --- a/src/sled/event_bus/event_bus.h +++ b/src/sled/event_bus/event_bus.h @@ -124,11 +124,19 @@ public: EventRegistry::Instance().Post(this, std::forward(event)); } + template + void PostTo(From &&value) + { + using U = internal::RawType; + EventRegistry::Instance().Post(this, std::forward(value)); + } + // On ([](const Event1 &){}) - template> + template typename std::enable_if::value>::type Subscribe(C *instance, void (C::*method)(Event)) { + using U = internal::RawType; { sled::MutexLock lock(&mutex_); auto iter = cleanup_handlers_.find(std::type_index(typeid(U))); @@ -140,9 +148,10 @@ public: EventRegistry::Instance().Subscribe(this, instance, method); } - template> + template typename std::enable_if::value>::type Unsubscribe(C *instance) { + using U = internal::RawType; EventRegistry::Instance().Unsubscribe(this, instance); { sled::MutexLock lock(&mutex_); diff --git a/src/sled/event_bus/event_bus_test.cc b/src/sled/event_bus/event_bus_test.cc index bf706b8..1c7c9ba 100644 --- a/src/sled/event_bus/event_bus_test.cc +++ b/src/sled/event_bus/event_bus_test.cc @@ -37,7 +37,7 @@ struct Subscriber : public sled::EventBus::Subscriber<> { TEST_SUITE("EventBus") { - TEST_CASE("RawType") + TEST_CASE("RawType built-in type") { CHECK(std::is_same>::value); CHECK(std::is_same>::value); @@ -52,6 +52,23 @@ TEST_SUITE("EventBus") CHECK(std::is_same>::value); } + TEST_CASE("RawType user-defined type") + { + struct A {}; + + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + CHECK(std::is_same>::value); + } + TEST_CASE("single thread") { sled::EventBus bus; @@ -142,6 +159,8 @@ TEST_SUITE("EventBus") TEST_CASE("same type") { struct Event { + Event(int v) : a(v) {} + int a; }; @@ -163,5 +182,8 @@ TEST_SUITE("EventBus") bus.Post(e); CHECK_EQ(subscriber1.a, 2); CHECK_EQ(subscriber2.a, 2); + bus.PostTo(1); + CHECK_EQ(subscriber1.a, 3); + CHECK_EQ(subscriber2.a, 3); } }