Skip to content

Instantly share code, notes, and snippets.

@benben
Created July 4, 2011 12:18
Show Gist options
  • Save benben/1063279 to your computer and use it in GitHub Desktop.
Save benben/1063279 to your computer and use it in GitHub Desktop.
factory with parameters
#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 desc;
Object1(std::string name, int x, int y) { desc = name; }
std::string hello() const { return "Hi, Object1, " + desc; }
};
struct Object2 : Parent {
template <typename T1, typename T2, typename T3> Object2(T1, T2, T3) {}
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(std::string, int, int)> > FactoryMap;
FactoryMap f;
Factory() {
using boost::phoenix::new_;
using boost::phoenix::construct;
using namespace boost::phoenix::arg_names;
f["Object1"] = construct<ParentPtr>(new_<Object1>(arg1, arg2, arg3));
f["Object2"] = construct<ParentPtr>(new_<Object2>(arg1, arg2, arg3));
// ...
}
ParentPtr operator()(std::string const & type, std::string name, int x, int y) const {
FactoryMap::const_iterator it = f.find(type);
if (it == f.end()) throw bad_type_exception();
return it->second(name, x, y);
}
};
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, "named-" + type, 9001, 3));
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