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: 
By declaring special empty classes for colors, you can do everything using templates. This requires every color choice to be made available at compile-time. By doing this, you avoid having to use a base class with virtual methods.

```
struct Red{};
struct Blue{};

template < typename Color >
class Pen{};

template <>
class Pen< Red >
{
     void Draw(){
         cout << "Drawing with red pen" << endl;
     }
};

template <>
class Pen< Blue >
{
     void Draw(){
         cout << "Drawing with blue pen" << endl;
     }
};

template < typename Color >
std::auto_ptr< Pen< Color > > createPen()
{
     return auto_ptr< Pen< Color > >(new Pen< Color >());
}

```
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.