CodeShop

Sparkx Embedded Maps

May 18th, 2009

Showcase for Sparkx - Maps:

object_factory

May 17th, 2009

For some reason, I needed a object factory. Well, that’s easy you might think: this subject is well understood and textbook material.

It turns out differently.

There are in fact several places where you can look: - Loki - Codeproject - Boost Sandbox

But these are all either too specialized or too generalized: nothing fitted quite what I needed: an object factory that creates objecst based on the types of the constructor parameters …

For example:


typedef ObjectFactory<base* (int, float), short> factory_t;

where base* (int, float) is the constructor signature, and short is the key (but you could use std::string just as easily).

The best solution was to be found on Gamedev

But this too needed a bit of attention: I wanted N constructor parameters, without having to specialize them by hand – as that would be silly.

So, with the help of Boost.Preprocessor I came up with the following.

The template is here

The template is specialized once for a constructor without arguments, and with the use of Boost.Preprocessor N times; well, between LIMIT_LOWER_BOUND and LIMIT_UPPER_BOUND – which you can adjust if you need more …

The above will allow for code like this unit-test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct base {};

struct node1 : public base
{
  node1(int) 
  { std::cout << "node1(int)" << std::endl; }
  
  node1(int, float) 
  { std::cout <<"node1(int, float)" << std::endl; }
};

void test_object_factory()
{
  std::wcout << L"object_factory_test: " << std::endl;
  
  typedef ObjectFactory<base* (int, float),
     char*> node1_factory_t;
  
  node1_factory_t nf;
  nf.Register<node1>("node1");

  base* n1 = nf.Create("node1", 2, 3.0);
  delete n1;

This would create an object with the (int, float) signature.