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: 
Your factory is fine. I take it the `BluePen` and so on were just example class names. You can use templates, if the following condition is met:

> 
> When you know at compile time (i.e when you write code) that you want a specific type returned, then use a template. Otherwise, you can't.
> 
> 
> 

That means in code, that you can do this:

```
template<typename PenType>
auto_ptr<Pen> createPen(){
    return auto_ptr<Pen>(new PenType);
}

```

Having that in place, you can then use that like

```
...
auto_ptr<Pen> p = createPen<BluePen>();
...

```

But that template-argument, the `BluePen`, can't be a variable that is set to a type at runtime. In your example, you pass a string, which can of course be set at runtime. So, when you read that you can use C++ Templates, then that recommendation is only conditionally true - then, when your decision, of which pen to create, is already done at compile time. If that condition fits, then the template solution is *the* right thing to do. It will not cost you anything at runtime, and will be exactly what you need.
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 >());
}

```