Question: I have the following code for "factory" design pattern implementation.

```
class Pen{
public:
     virtual void Draw() = 0;
};

class RedPen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with red pen" << endl;
     }
};

class BluePen : public Pen{
public:
     virtual void Draw(){
         cout << "Drawing with blue pen" << endl;
     }
};

auto_ptr<Pen> createPen(const std::string color){
     if(color == "red")
         return auto_ptr<Pen>(new RedPen);
     else if(color == "blue")
         return auto_ptr<Pen>(new BluePen);
}

```

But I heard that it can be done in a better way using "C++ templates". Can anyone help how it is done and how template approach is better than this?

Any thoughts

Answer: 
You could write a generic object factory class as a template class (or use the one nicely described in this [gamedev.net article](http://www.gamedev.net/page/resources/_/technical/general-programming/creating-a-generic-object-factory-r2097)).

This way, if you have more than one factory in your code, it is less work to define each factory.
As a supplement to my other answer, just to discuss the Factory pattern vs. template useage:

The main (and simplest) reason to use templates, is that your code is identical in every case, except for the data types it works on. Examples here are the STL containers.
It would be possible to write a factory function createVector("string"), and type out each container manually -- but this is clearly sub-optimal.

Even when code differs, not only data types, it's possible to use template specializations -- but in many cases, a factory function would make more sense.

As an example, consider a database abstraction library. It would be possible to use template specializations, so that the library could be used like "db::driver". But this would force you to type out the database type everywhere in the code (making the library kinda useless in the first place...), or perform a case to an interface type db::driver class.

In this example, it's more intuitive to say db::get\_driver(odbc) and get back the proper class cast to the interface type.