Question

Serialization of a template data type

Asked by: edc

Hello experts,
In my code sample below I have a class declaration to add data of unknown type to a file.  The data is passed in as a parameter, and the code will be multi-platform.  My question is, how can I serialize this data so that it can be written out to a file?

Thanks very much.

class Resource
{
public:
	Resource(void);
	~Resource(void);
 
	template<typename ResourceType> 
	static void AddResource(std::string resourceName, ResourceType resourceType, std::string resourceValue);	
};

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-17 at 08:35:03ID24740222
Tags

C/C++

Topic

C++ Programming Language

Participating Experts
2
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Serializing
    The prime requirement for an object to be serialized is that it should be derived from CObject class. But 'CString' class is not derived from CObject. How it's still possible the CString objects ? Adv. thanks!
  2. Serialization
    What is Object Serialization..?? What exactly happens when we serialize objetcs..and when to use serialization of objects.
  3. serialization?
    what is serialization? i've heard this term many times but i have no idea what it is :)
  4. program serial data
    Hi! I am new here. Any help would be very appreciated. My project involves connecting from position tracker device (when ON, it outputs position data) to PC through serial port. When I use Hyperterminal, it can interpret the data and convert it to ASCII format for user to r...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: evilrixPosted on 2009-09-17 at 09:40:25ID: 25358143

>> how can I serialize this data so that it can be written out to a file?
The problem with serialising template types is you don't know what they are. If they are PODs (plain old data... intrinsics types such as int or char classes/structs with no virtual functions, constructors or embedded non-pods [the definition is more stringent than this but you can Google for it I'm sure]) You can just use an ofstream to write them out using the write method. If they are more complex types you need to implement a specific serialisation policy for the type. If the types are never going to be PODs and always user defined types either overload namespace level operator <<(ostream &, <yourtype> &) or implement serialise and deserialise methods on your class.

 

by: evilrixPosted on 2009-09-17 at 09:42:02ID: 25358166

Also, you might want to take a look at Boost serialisation. It might help you out.
http://www.boost.org/doc/libs/1_40_0/libs/serialization/doc/index.html

 

by: edcPosted on 2009-09-17 at 13:46:42ID: 25360891

Thanks very much for the info evilrix.  I've read through some of the documentation on Boost.  Do you happen to have a pointer to an example that handles templated data up your sleve by any chance?

Thanks again.

 

by: evilrixPosted on 2009-09-18 at 00:14:18ID: 25363435

At best I can only give you a generalised  solution for the POD types

WARNING: Remember this can only safely be used for PODs and if the object contains pointers of references to other objects they won't be persisted since it is a shallow copy. Sue with care.

http://en.wikipedia.org/wiki/Plain_old_data_structures
http://www.informit.com/guides/content.aspx?g=cplusplus&amp;seqNum=32
http://www.devx.com/tips/Tip/12970

   template <
      typename dataT,
      typename istreamT = std::ifstream,
      typename ostreamT = std::ofstream
   >
   class Serializer : public SerializerBase
   {
   public:
      bool Serialise(std::string const & key, dataT const & data) const
      {
         ostreamT oStream(key.c_str(), std::ios::binary | std::ios::trunc);
         bool bOk = oStream.is_open();
 
         if(bOk)
         {
            oStream.write(reinterpret_cast<char const *>(&data), sizeof(data));
            bOk = oStream.good();
            oStream.close();
         }
 
         return bOk;
      }
      
      bool Deserialise(std::string const & key, dataT & data) const
      {
         istreamT iStream(key.c_str(), std::ios::binary);
         bool bOk = iStream.is_open();
 
         if(bOk)
         {
            iStream.read(reinterpret_cast<char *>(&data), sizeof(data));
            bOk = iStream.good();
            iStream.close();
         }
 
         return bOk;
      }
   };
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: itsmeandnobodyelsePosted on 2009-09-18 at 01:33:34ID: 25363805

>>>> UseWARNING: Remember this can only safely be used for PODs
A method that works both for POD and class types (only if POD types have same size for all particpients) is to have global serialize and deserialize functions for each type supported, e. g.

archive & serialize(archive & aout, const int& i)
{
     int hi = htonl(i);
     return aout.write(&ui, sizeof(int));
}

...

archive & serialize(archive & aout, const A& a)
{
     aout.serialize(aout, a.i_member);
     aout.serialize(aout, a.str_member);
     aout.serialize(aout, a.dbl_member);
     aout.serialize(aout, a.otherclass_member);
     return aout;
}

You even could serialize pointer or array members that way though of course not as pointers but by serializing the object the pointer is pointing to.







 

by: evilrixPosted on 2009-09-18 at 02:04:57ID: 25363973

I'm pretty certain I've already said as much...

"If the types are never going to be PODs and always user defined types either overload namespace level operator <<(ostream &amp;, <yourtype> &amp;) or implement serialise and deserialise methods on your class.

{http:#25358143}

 

by: edcPosted on 2009-09-18 at 07:23:21ID: 31630081

Thanks!  I believe I understand all the issues involved now.

 

by: itsmeandnobodyelsePosted on 2009-09-18 at 09:39:52ID: 25367685

>>>> either overload namespace level operator <<(ostream &amp;, <yourtype> &amp;)
Overloading the ostream operator is less recommended as general output rarely is suitable for serializing and you reasonably can only have one global operator<< implementation for a type. But of course you could overload the operator<< and operator>> for your own archive class instead of using functions serialize/deserialize

class archive
{
    unsigned char buf*;
    unsigned int sizalloc;
    unsigned int sizfilled;
public:
    archive() : buf(NULL), sizalloc(0), sizfilled(0) {}
    friend operator<<(archive & ar, const int& i)
    {
         ar.write(&i, sizeof(int));
         return ar;
    }
    // add more operator<< overloads for POD types
    void write(void * p, int siz)
    {
         if (sizalloc < sizfilled + siz)
        {
              unsigned char* newbuf = new unsigned char[sizalloc + CHUNK_SIZ];
              if (buf != NULL)  
                 memcpy(newbuf, buf, sizalloc);
              memset(&newbuf[sizalloc], 0,  CHUNK_SIZ);
              delete []buf;
              newbuf = buf;
              sizalloc += CHUNK_SIZ;
         }
         memcpy[&buf[sizfilled], p, siz];
         sizfilled += siz;
    }
};

archive & operator<<(archive & aout, const A& a)
{
     aout << a.i_member << a.str_member <<  a.dbl_member << a.otherclass_member;
     return aout;
}


>>>> or implement serialise and deserialise methods on your class.
class members are a means to have serializing for class types only. My suggestion was to using global serialize/deserialize functions in order to have a universal solution for POD types and non-POD types.

I used that method in a few projects with good success.

 

by: evilrixPosted on 2009-09-18 at 13:47:53ID: 25369851

>> Overloading the ostream operator is less recommended as general output
Authoritative reference?

>> reasonably can only have one global operator<< implementation for a type.
Use an adapter or a stream manipulator if this is really a valid use-case.

>> for serializing and you reasonably can only have one global operator<<
It is important you place the operators in the same namespace as the class they are designed to serialise and deserialise to avoid ambiguities with other types that may share the same name. You can rely on ADL (Argument Dependent Lookup) to ensure the correct operator is called without having to fully quality the operator with the namespace.
http://en.wikipedia.org/wiki/Argument_dependent_name_lookup

>> My suggestion was to using global serialize/deserialize functions in order to have a universal solution for POD types and non-POD types.
Intrinsics already have overloaded stream operators, for you own user defined struct/class you just need to overload namespace level stream operators. This keeps things nice and simple; you can then serialise to any type of stream that supports the standard istream and ostream interfaces without writing any addition code or changing any syntax/semantics. You can also template the namespace level stream operators to provide more generic behavior.





 

by: evilrixPosted on 2009-09-18 at 13:49:17ID: 25369859

>> // add more operator<< overloads for POD types
Why not just use a template as I did above? You then only need to write one function, specializing if necessary for other types.

 

by: itsmeandnobodyelsePosted on 2009-09-19 at 00:14:19ID: 25371854

>>>> I'm pretty certain I've already said as much...
I was missing your pardon about wrongly accusing me to have repeated what you already said ...  


>>>> Overloading the ostream operator is less recommended as general output
>> Authoritative reference?
It is a practical advise by me. I have done serialising in various projects and mixing up output streaming with serialisation has not one single benefit. You need the operator<< for (normal) outputs and it is not senseful to using different implementations or manipulators as it makes things unnecessarily complex (thus error-prone). Instead of using the ostream class it is much more straight-forward to using an archive class as you have to care for the archive (e. g. by handling endianess issues) in a special way anyhow. If you did that once, you would know that streaming is one of the minor issues to care for.

>>>> you just need to overload namespace level stream operators. This keeps things nice and simple
Truly simple. Playing around with namespaces is a sure method to precipitate a project into desaster. How will you find out whether the right implementation was used in code of some millions of lines?  

 

by: evilrixPosted on 2009-09-19 at 01:27:04ID: 25372059

ADL takes care of resolving this for you, the right version will always be used -- the rules of ADL are pretty simple to learn.

Overloading standard operators in the global namespace (especially templating them as the asker is implying here) really is a recipe to disaster. By namespacing your code properly ADL will ensure the correct operator is utilized. ADL was added to the C++ standard to solve exactly this type of problem.


http://www.cplusplus.com/doc/tutorial/namespaces/
http://codeidol.com/cpp/cpp-common/Argument-Dependent-Lookup/

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...