C++ Abstract Classes + Serialization

Interestingly I had to delete my last post. Firefox and IE both tried to consume all of my memory when I tried to edit it. Anyway, I am working on trying to understand the “best” way to do serialization/deserialization of child classes of an abstract class. Here is what I came up with so far.

#if !defined(CFILTERFACTORY_H)
#define CFILTERFACTORY_H

#include <gtkmm.h>
#include <map>
#include <iostream>

#include "CFilter.h"
#include "CMedianFilter.h"
#include "CAverageFilter.h"
#include "CException.h"

typedef CFilter *(*FactoryFunc)(std::istream&);

class CFilterFactory
{
public:
  CFilterFactory();    // constructor

  // add a new type to the factory
  void addFilterType(Glib::ustring name, FactoryFunc fptr);
  CFilter* deserializeFilter(std::istream&) throw (CException);

private:
  // deserialize function mapping
  std::map<Glib::ustring, FactoryFunc> funcMap;
};

#endif /* CFILTERFACTORY_H */


And the implementation:


#include "CFilterFactory.h"

CFilterFactory::CFilterFactory()
{
  // built-ins, add others as needed
  addFilterType("average", CAverageFilter::deserialize);
  addFilterType("median", CMedianFilter::deserialize);
}

CFilter* CFilterFactory::deserializeFilter(std::istream& input) throw (CException)
{
  Glib::ustring name;
  // TODO:
  //  1. parse xml to find type
  //  2. look for constructor appropriate for type
  //  3. throw exception if it is not found, else call it!
  if(funcMap.find(name) == funcMap.end())
  {
    throw CException(-1, "Unknown filter type");
  }
  // TODO: probably needs to be called on an XML tree instead (or a string?)
  return funcMap[name](input);
}

void CFilterFactory::addFilterType(Glib::ustring name, FactoryFunc fptr)
{
  funcMap[name] = fptr;
}


So the idea is to use a factory class to marry the strings to the static constructor functions. I could have used a switch-case to map the functions, but I wanted to be able to possibly generate new, user-scriptable filters at run time.

2 Responses to “C++ Abstract Classes + Serialization”

  1. Jack Says:

    I’m glad to see you found a solution for this, this looks like a good way to do it. After looking at it though, I will have to admit I’m spoiled writing managed code all the time. :)

  2. Jack Altiere » Using the Factory Pattern Says:

    [...] was using C++ and he eventually came up with a good solution to the problem, but it got me wondering how I would handle the same requirements using C#.  [...]

Leave a Reply