Skip to content

Instantly share code, notes, and snippets.

@benben
Forked from pyrtsa/factory.cpp
Created June 28, 2011 16:53
Show Gist options
  • Save benben/1051577 to your computer and use it in GitHub Desktop.
Save benben/1051577 to your computer and use it in GitHub Desktop.
Object factory using Boost.Phoenix, Boost.Function and Boost.SmartPtr libraries
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <map>
#include <string>
#include <vector>
struct Parent { virtual std::string hello() const = 0; };
struct Object1 : Parent { std::string hello() const { return "Hi, Object1"; } };
struct Object2 : Parent { std::string hello() const { return "Ay, Object2"; } };
struct bad_type_exception : std::exception {
char const * what() const throw() { return "No such class!"; }
};
typedef boost::shared_ptr<Parent> ParentPtr;
struct Factory {
typedef std::map<std::string, boost::function<ParentPtr()> > FactoryMap;
FactoryMap f;
Factory() {
using boost::phoenix::new_;
using boost::phoenix::construct;
f["Object1"] = construct<ParentPtr>(new_<Object1>());
f["Object2"] = construct<ParentPtr>(new_<Object2>());
// ...
}
ParentPtr operator()(std::string const & type) const {
FactoryMap::const_iterator it = f.find(type);
if (it == f.end()) throw bad_type_exception();
return it->second();
}
};
int main() {
Factory factory;
std::vector<std::string> types;
types.push_back("Object1");
types.push_back("Object2");
std::vector<ParentPtr> items;
BOOST_FOREACH(std::string const & type, types)
items.push_back(factory(type));
BOOST_FOREACH(ParentPtr item, items)
std::cout << item->hello() << std::endl;
// Prints:
// Hi, Object1
// Ay, Object2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment