From 0fe83d59d76cd8f9c8f92d40cc58d9f5b082a84a Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Wed, 31 Aug 2016 18:27:43 +0900 Subject: Event::fromJson(): made the code more compact That might be not as efficient as a solution on variadic templates; but arguably easier to understand. --- events/event.cpp | 55 ++++++++++++++++++++++++------------------------------- 1 file changed, 24 insertions(+), 31 deletions(-) (limited to 'events/event.cpp') diff --git a/events/event.cpp b/events/event.cpp index d05d666f..1235780d 100644 --- a/events/event.cpp +++ b/events/event.cpp @@ -82,40 +82,33 @@ QString Event::originalJson() const return d->originalJson; } +template +Event* make(const QJsonObject& obj) +{ + return T::fromJson(obj); +} + Event* Event::fromJson(const QJsonObject& obj) { - //qDebug() << obj.value("type").toString(); - if( obj.value("type").toString() == "m.room.message" ) - { - return RoomMessageEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.room.name" ) - { - return RoomNameEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.room.aliases" ) - { - return RoomAliasesEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.room.canonical_alias" ) - { - return RoomCanonicalAliasEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.room.member" ) - { - return RoomMemberEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.room.topic" ) - { - return RoomTopicEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.typing" ) - { - return TypingEvent::fromJson(obj); - } - if( obj.value("type").toString() == "m.receipt" ) + struct Factory { + QString type; + Event* (*make)(const QJsonObject& obj); + }; + const Factory evTypes[] { + { "m.room.message", make }, + { "m.room.name", make }, + { "m.room.aliases", make }, + { "m.room.canonical_alias", make }, + { "m.room.member", make }, + { "m.room.topic", make }, + { "m.room.typing", make }, + { "m.room.receipt", make }, + // Insert new types before this line + }; + for (auto e: evTypes) { - return ReceiptEvent::fromJson(obj); + if (obj["type"].toString() == e.type) + return e.make(obj); } return UnknownEvent::fromJson(obj); } -- cgit v1.2.3