0

I have a class hierarchy that uses template:

template <typename T>
class BaseClass
{
public:
    BaseClass(const std::string& inputName)
        :
        myMember(std::make_shared<T>(inputName))
    {}
private:
    const std::shared_ptr<T> myMember;
};

class UsedByDerived 
{
public:
    UsedByDerived(const std::string& inputName)
        :
        myInputName(inputName)
    {}
private:
    const std::string myInputName;
};

class DerivedClass : public BaseClass<UsedByDerived>
{
public:
    DerivedClass()
        :
        BaseClass<UsedByDerived>("X")
    {}
};

I have multiple derived classes like this (each could have different constructor signatures), and I would like to do an abstract factory to handle the instantiation. The base factory is

template <typename T>
class BaseFactory
{
public:
    virtual std::shared_ptr<BaseClass<T>> createProduct() = 0;
};

I'm wondering what the derived factory class should look like (or whether this is not going to work?), however it's not clear how it should be implemented...:

class DerivedFactory
{
public:
    std::shared_ptr<BaseClass</* what should this be? */>> createProduct()
    {
        // what should this return?
    }
};
PF Chang
  • 47
  • 6

2 Answers2

0

There's little point defining BaseFactory<T>, because BaseFactory<Derived1> is a distinct type to BaseFactory<Derived2>.

Similarly BaseClass<T>. Different instantiations are not interchangeable.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Thanks. How would you suggest that this is handled? I really don't want to do explicit case switching on the client side. – PF Chang Mar 20 '20 at 09:17
  • What are the non-template members of `BaseClass`? You might be able to split it into a non-template interface and template abstract class. – Caleth Mar 20 '20 at 09:19
-1

As python methodology will beckon, We're are all adults here.. You can make a template factory class. But should you?

To answer this you need to consider that the Factory paradigm was designed to treat objects like a car and a car factory.

You get a BMW from a BMW factory. When it needs a service you take it back to the BMW factory. The factory will handle modifications and fixes.

If you do take it to a Mercedes factory, BMW aren't going to be very happy with you. Because they designed their car to be fast and safe. Mercedes just wants it to be safe. So they downsized your engine and stripped away the body kit. And now BMW no longer understands how to fix the car if it breaks. So the BMW factory doesn't work anymore.

It's better to have a list of multiple different factories than to have a single factory for a list of multiple different cars.

What might ease the pressure on contorting this class however is to combine the factory pattern with a visitor pattern or even the decorator pattern. Or both. This will let you add responsibility to your classes without changing them.

You could even use the visitor/decorator pattern on the factories.

Parthanon
  • 388
  • 2
  • 7