Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » U++ Library support » U++ Core » Convert struct to string and reconstruct a struct from string
Re: Convert struct to string and reconstruct a struct from string [message #55326 is a reply to message #55325] Fri, 30 October 2020 13:14 Go to previous messageGo to previous message
Didier is currently offline  Didier
Messages: 725
Registered: November 2008
Location: France
Contributor
After trying it out,

here is the same exmaple with small compilation corrections (compiles on Clang linux)

#include <Core/Core.h>



namespace Upp {
	
struct AMessage {
   virtual void Serialize(Stream& s) = 0;
   virtual ~AMessage() {}
};

typedef Function< void (One<AMessage>&) > MessageMake;

VectorMap<int, MessageMake> message_maker;

template <class T>
void RegisterMessage(int messageid)
{
    message_maker.Add(messageid, [](One<AMessage>& m) { m.Create<T>(); });
}


// =============================
//     Messages definition
// =============================
struct TemperatureMessage : AMessage {
   double altitude, temperature;

   virtual void Serialize(Stream& s) {
       s % altitude % temperature;
   }
};


struct WarningMessage : AMessage {
   String text;

   virtual void Serialize(Stream& s) {
       s % text;
   }
};



// =============================
//     Message registeration
// =============================


INITBLOCK {
   RegisterMessage<TemperatureMessage>(1); // do that for all of your messages
   RegisterMessage<WarningMessage>(2); // do that for all of your messages
};




void ProcessRequest(const String& data)
{
   StringStream ss(data); // error handling for now omitted
   int client_id = ss.Get32();
   int message_id = ss.Get32();
   One<AMessage> m;
   int q = message_maker.Find(message_id);
   if(q < 0)
      return;
   (message_maker[q])(m); // create the required concrete message
   ss % *m; // load data to struct
}

}
using namespace Upp;

CONSOLE_APP_MAIN
{
}
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Looking for examples to split string into container
Next Topic: What does this compiling error mean exactly?
Goto Forum:
  


Current Time: Sat Apr 26 22:24:01 CEST 2025

Total time taken to generate the page: 0.00613 seconds