The Artima Developer Community
Sponsored Link

Heron-Centric: Ruminations of a Language Designer
Automated Serialization using Templates
by Christopher Diggins
September 9, 2005
Summary
Here is a pattern I call the Bus Pattern. It's like the Visitor Pattern, except it's not.

Advertisement

I am probably reinventing the wheel, but here goes nothing. Given the following class:

  MyClass {
    ClassA a;
    ClassB c
    ClassC c
  } 
Let's say you want to stream the thing to XML. Simply add the following function:
  template<typename Bus> 
  void GetOnTheBus(Bus bus) {
    bus(a);
    bus(b);
    bus(c);
  }
Now you could write an XML streaming mechanism like this:
  class ToXmlBus {
  public:
    template<typename T>
    operator()(T& x) {
      x.GetOnTheBus();
    }
    operator()(int& n) {
      cout << "<int>" << n << "</int>";
    }
    operator()(char& c) {
      cout << "<char>" << n << "</char>";
    }
    ...
  }
  class FromXmlBus {
  public:
    template<typename T>
    operator()(T& x) {
      x.GetOnTheBus();
    }
    operator()(int& n) {
      cin >> "<int>" >> n >> "</int>";
    }
    operator()(char& c) {
      cin >> "<char>" >> n >> "</char>";
    }
    ...
  }
Cool isn't it? Now I can't be the first person to name this, can anyone point me in the right direction?

Talk Back!

Have an opinion? Readers have already posted 6 comments about this weblog entry. Why not add yours?

RSS Feed

If you'd like to be notified whenever Christopher Diggins adds a new entry to his weblog, subscribe to his RSS feed.

About the Blogger

Christopher Diggins is a software developer and freelance writer. Christopher loves programming, but is eternally frustrated by the shortcomings of modern programming languages. As would any reasonable person in his shoes, he decided to quit his day job to write his own ( www.heron-language.com ). Christopher is the co-author of the C++ Cookbook from O'Reilly. Christopher can be reached through his home page at www.cdiggins.com.

This weblog entry is Copyright © 2005 Christopher Diggins. All rights reserved.

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use