Subclass object as a parameter to a virtual function - c++

Ok, so basically I have a class in use in another class which, among other things, asks on object to report on its relationship to another object of the same type. Works great. FYI this class represents a protocol. Unfortunately, now I'm trying to decorate the class relationship by adding a class called a Wrapper. The main power of this class is that it can take the first class as an argument (or anything else that does the same).:
template< class InnerInterpreter >
class WrapperInterpreter
{
public:
WrapperInterpreter(const InnerInterpreter &m) : innerMessage(m) {}
...
virtual bool respondsToMessage(const WrapperInterpreter<InnerInterpreter> &) const = 0;
public:
//member
InnerInterpreter innerMessage;
};
What I've concluded for other design reasons is that having this as a base class to a set of wrappers (rather than taking two different protocols as arguments) allows me a combinatorial set of outer and inner protocol classes.
So here's my problem: When I try to subclass WrapperInterpreter<>, and in particular provide an implementation to respondsToMessage(), I end up with a subclass that is able to compare to any class in the WrapperInterpreter heirarchy. But that's not actually what I want to do. What I would like to do is to force the subclass to implement a method thusly:
template< class Inner >
class ConcreteWrapper : WrapperInterpreter<Inner>
{
...
bool respondsToMessage(const ConcreteWrapper<Inner> &);
...
}
One solution I came to immediately was to simply remove it from the interface of WrapperInterpreter and just let the compiler complain about the missing interface method only when in use with the rest of the design.
So my question is: is there any way to put a method in an abstract class's interface, such that the subclass must take an object of the subclass type as a parameter?
Alternatively, am I trying to use inheritance incorrectly? Does anybody have any useful design patterns that might help me to address this problem?

There is a design called CRTP (Curiously Recurring Template Pattern) which consists in passing the type of the Child to the Parent as a template parameter:
template <typename Child>
class WrapperInterpreter {
using Inner = typename Child::Inner; // nested typedef
WrapperInterpreter(Inner const& ...);
virtual bool respondsToMessage(Child const& ...) = 0;
};
template <typename Inner>
class Concrete: public WrapperInterpreter< Concrete<Inner> > {
virtual bool respondsToMessage(Concrete const& ...) override;
};

Related

Derived class template

I have some question on derived class templates. I have base and derived class templates like this:
// This is base class
class CParameter {
public:
CParameter(std::string name) : name(name) {}
// virtual ~CParameter() {} // deleted for good design:)
public:
std::string name;
};
...
// This is derived class
template <typename T>
class CTemplateParameter : public CParameter {
public:
CTemplateParameter(std::string name) : CParameter(name) {}
public:
T parameter;
};
and I declare some type parameters the push them to base class vector
//Base class parameters
std::vector<CParameter*> parameters; // !
CTemplateParameter<CMatrix4<float>> mat4;
CTemplateParameter<CVector3<float>> vec3;
CTemplateParameter<float> flt;
parameters.push_back(mat4);
parameters.push_back(vec3);
parameters.push_back(flt);
I have template SetParameter function:
// This method moved to CParameter base class
template <typename T>
bool SetParameter(const CTemplateParameter<T>& param) {
// switch(typeof(T)) {
// set parameter
if (std::is_same<T, int>::value)
// gLUniform1i(...)
else if (std::is_same<T, CMatrix4<float>>::value)
// glUniformMatrix4fv(..)
...
}
So my questions:
1) How to set all parameter individual?
// Notice this function is not template
void SetAll() {
for each parameter
SetParameter(parameter[i])
}
2) Without enum, can I get type of parameter and create a type in run time? Like:
Pseudo code:
//get type of parameter[i]
//create a parameter from
T type = GetTypeofParameter(parameter[i]);
CTemplateParameter<type> newType;
3) Can i get a derived class type like this or how to cast?
CTemplateParameter<void*>* p = dynamic_cast<CTemplateParameter<void*>>(parameters[i]);
Thanks so much.
My comments seem to have pushed ADesignersEncyclopedia away from a template/virtual mix but not toward a practical alternative. The original question doesn't give enough info to decide whether there is a practical alternative. Lacking such a practical alternative, do the virtual/template mix correctly (with CRTP) rather than reject it entirely:
In your target class, you want setParameter in two forms, neither of which is a template. The first form dispatches to the setParameter inside the parameter class, which dispatches back to the second form in the target class:
bool SetParameter(const CParameter& param) {
return param.SetParameter( *this );
}
The second form is overloaded on the value type:
bool SetParameter(int value) {
// whatever
}
bool SetParameter(CMatrix4<float> const& value) {
// whatever
}
...
In your parameter base class, you want SetParameter pure virtual
class CParameter
{
...
virtual bool SetParameter( TargetType& ) const = 0;
...
};
Then you need a CRTP base class, which should be derived from your simple base class:
template<class ActualType>
class CRTPParameter : public CParameter
{
CRTPParameter(std::string name) : CParameter(name) {}
ActualType* This() {return static_cast<ActualType*>(this); }
ActualType const* This() const {return static_cast<ActualType const*>(this); }
// various things including
ActualType* clone() const { return new ActualType( *This() ); }
bool SetParameter( TargetType& target ) const
{ return target.SetParameter( This()->parameter ); }
};
Then your template class derives from your CRTP class
template <typename T>
class CTemplateParameter : public CRTPParameter<CTemplateParameter<T> > {
public:
typedef CRTPParameter<CTemplateParameter<T> super;
CTemplateParameter(std::string name) : super(name) {}
If everything else is simple enough, then the whole CRTP scheme might be overkill and you could just move clone and SetParameter from CRTPParameter to CTemplateParameter and go back to not having CRTPParameter.
But in my experience with such structures, things soon get messy in CTemplateParameter in ways that a best dealt with by the extra layer.
1/
You should define setParameter in Cparameter as an abstract method, and implement it in your template class.
2/
I suggest to use a clone(or a factory) method, defined as I suggested in 1/. In this method you can copy(or create) your object then define it.
3/
No. You can't cast CtemplateParameter<float> to CtemplateParameter<void*>
1) How to set all parameter individual?
You can't iterate and set the value for all of them, unless you know the type. And put a huge amount of dynamic_cast would not be the solution either as it is not scalable.
One solution would be to keep a map of std::function. These function would not take any parameter and return nothing. They will set the parameter with the right values. Pushing into the vector would be like this:
std::map<CParameter*, std::function<void()>> mySets;
// ...
mySets.emplace(&parameter, [ObjectThatGiveMeNext, &parameter]() {
parameter.setParameter(ObjectThatGiveMeNext.get());
});
Even if you contain the parameter, it is not your main container for parameters. It is only to keep track of which parameter is associated to which function.
The ideal would be to create this function when you create the parameter, because you know the type of the parameter there.
Another solution would be to create a virtual function updateValue that would call setParameter with this.
2) Without enum, can I get type of parameter and create a type in run time?
That is not really possible it's a context where you don't know the type, so you must either know the type (a switch case) or rely on polymorphic behaviour. I think the best here is to rely on polymorphic behaviour.
I would add a virtual function clone for that. Maybe not the famous straight clone function, but a clone function that return both the parameter and the function to set it's value. Something a bit like that:
std::tuple<std::unique_ptr<CParameter>, std::function<void()>> clone();
Consider a typedef or using in this case as the type is loooooong.
3) Can i get a derived class type like this or how to cast?
No you can't. You would need to convert the instance of your class to another, not related type. I would not do that. Instead, keep your code that deal with your specific derived class where you explicitely know the type and keep the generic code generic (eg: not trying to know the type). This is the best advice I can tell you right now.

Is there anything better than a metafactory to work around constructor injection into derived classes in CRTP?

In the CRTP, I want to inject the constructor into the derived class, cleanly - without use of macros and without writing it out. It seems it's impossible, so I've come up with some workarounds.
First, there's an underlying event class (QEvent) that should have a unique integer type tag for every derived class (see rationale). You obtain it by calling a registration function It's easy enough to create a CRTP wrapper that will hide this from you:
template <typename Derived> class EventWrapper : public QEvent {
public:
EventWrapper() : QEvent(staticType()) {}
static QEvent::Type staticType() {
static QEvent::Type type = static_cast<QEvent::Type>(registerEventType());
return type;
}
};
class MyEvent1 : public EventWrapper<MyEvent1> {}; // easy-peasy
class MyEvent2 : public EventWrapper<MyEvent2> {};
Note that MyEvent1::staticType() != MyEvent2::staticType(): registerEventType() returns unique types each time it's called.
Now I want the event class to carry some data:
template <typename Derived> class StringEvent : public EventWrapper<D> {
std::string m_str;
public:
explicit StringEvent(const std::string & str) : m_str(str) {}
std::string value() const { return m_str; }
};
But here we run into a problem: we need to manually define the constructor in each of the derived classes. The whole point here is that creation of such classes should be easy, as there may be many different string-carrying event types. But it's anything but easy:
class MyEvent3 : public StringEvent<MyEvent3> {
public: MyEvent3(std::string s) : StringEvent(s) {}
};
This obviously gets old real quick, even with C++11 constructor forwarding:
class MyEvent3 : public StringEvent<MyEvent3> { using StringEvent::StringEvent; };
What we'd want is a way of injecting this constructor into the derived class, or avoiding doing so while still providing for ease of use. Sure you can hide it in a preprocessor macro, but I hate those macros, they are a maintenance pain as they introduce new names for very simple concepts.
We can of course use a dummy type. Note that there's no need for a definition of the dummy type. It's only a name to be used as the type argument.
// Pre-C++11
class DummyEvent3;
typedef StringEvent<DummyEvent3> MyEvent3;
// C++11
class DummyEvent3;
using MyEvent3 = StringEvent<DummyEvent3>;
Another solution would be to use an int template argument and use an enum value, but this brings back the uniqueness issue that got solved by using the registerEventType() in the first place. It'd be no fun to guarantee that a large program is correct. And you'd still need to spell out the enum.
So, I've come up with a metaprogram class that I'll call a metafactory, that can produce the ready-to-use StringEvent classes for us, while keeping it all to one type definition:
// the metafactory for string events
template <typename Derived> class StringEventMF {
public:
class Event : public EventWrapper<Derived> {
std::string m_str;
public:
explicit Event(const std::string & val) : m_str(val) {}
std::string value() const { return m_str; }
};
};
or simply
template <typename Derived> class StringEventMF {
public:
typedef StringEvent<Derived> Event;
};
This is used like:
class Update : public StringEventMF<Update> {};
class Clear : public StringEventMF<Clear> {};
void test() {
Update::Event * ev = new Update::Event("foo");
...
}
The classes you use are Update::Event, Clear::Event. The Update and Clear are metafactories: they generate the desired event class for us. The derivation from the metafactory sidesteps derivation from the concrete class type. The metafactory type gives the unique type discriminator needed to create unique concrete class types.
The questions are:
Is there any "cleaner" or "more desirable" way of doing it? Ideally, the following non-working pseudocode would be my ideal way of doing it - with zero repetition:
class UpdateEvent : public StringEvent <magic>;
The name of the derived class appears only once, and the name of the base concept StringEvent appears only once, too. The CRTP requires the class name to appear twice - so far I think it's acceptable, but my metaprogramming-fu is in tatters. Again, I want a preprocessor-less solution, it'd be a no-brainer otherwise.
Is the name metafactory my original invention (ha ha), or is it merely my google-Fu that's lacking? This metafactory pattern seems to be quite flexible. It's easy to compose metafactories by multiple derivation. Say you wanted an Update::Event made by one factory, and Update::Foo made by another.
This question is motivated by this answer. Note: in real code I'd be using QString, but I'm trying to keep it as generic as possible.
I think what you're looking for might be just using placement new to instantiate the base class.
The derived class won't be constructable because unless they will create a matching constructor.
But, they don't have to be constructable, you could use them anyway. (It could still be destructable).
template <class T>
class Base
{
protected: Base(int blah) { }
public: static T* CreateInstance(int data) {
T* newOjectBlock = reinterpret_cast<T*>(::operator new(sizeof(T))); // allocate enough memory for the derived class
Base* newBasePlace = (Base*)(newOjectBlock); //point to the part that is reseved for the base class
newBasePlace= new ((char*)newBasePlace) Base(data); //call the placement new constrcutor for the base class
return newOjectBlock;
}
};
class Derived : public Base<Derived> {}
Then let the CRTP base class construct the derived class like this:
Derived* blah = Derived::CreateInstance(666);
If anyone ever wants to initialize the derived class, they should either make a matching constructor that calls the base class constructor.
OR, just make an .init() method that initiates its members, and will be called after the instance is created.
OR, we can think of something else, this is just an idea of a concept.
Yochai Timmer has come up with an alternative way of approaching the problem. Instead of having to forward the constructor from the data carrier class, he exposes a factory method that produces pseudo-derived classes. As it invokes undefined behavior, I'm not particularly keen on it.
Expanding a bit on the original metafactory concept, it's possible to make generic metafactory that can be used to make unique event types that wrap "any" data-carrying class.
The approach for C++11 uses constructor forwarding so that plain non-template data carrier classes can be used. The approach for C++98 requires a templated data carrier class and, internally, a bit more gymnastics, but it works as well.
The event classes can't be further derived from. This is necessary since the derived classes would all share the value of staticType, and that can't be allowed, as DyP duly noted in the comments.
To test the code, you need the event wrapper, the metafactory and data carrier selected for your variant of C++, and the test/usage part.
The Event Wrapper (Common Code)
In either case, our basic event wrapper CRTP class that generates a unique static type value for the event is:
// A type-identifier-generating wrapper for events. It also works with RTTI disabled.
template <typename Derived> class EventWrapper : public QEvent {
public:
EventWrapper() : QEvent(staticType()) {}
static QEvent::Type staticType() {
static QEvent::Type type = static_cast<QEvent::Type>(registerEventType());
return type;
}
static bool is(const QEvent * ev) { return ev->type() == staticType(); }
static Derived* cast(QEvent * ev) { return is(ev) ? static_cast<Derived*>(ev) : 0; }
};
Note that it also provides a cast-to-derived method. You'd use it in an event handler, given a pointer to a base event class:
void MyClass::customEvent(QEvent* event) {
if (MyEvent::is(event)) {
auto myEvent = MyEvent::cast(event);
// use myEvent to access data carrying members etc)
}
}
The C++98 Metafactory
The Carrier is a parametrized data carrier class, such as StringData below.
// The generic event metafactory
template <typename Derived, template <typename> class Carrier> class EventMF {
class EventFwd;
class Final;
class FinalWrapper : public EventWrapper<EventFwd>, public virtual Final {};
public:
// EventFwd is a class derived from Event. The EventWrapper's cast()
// will cast to a covariant return type - the derived class. That's OK.
typedef Carrier<FinalWrapper> Event;
private:
class EventFwd : public Event {};
class Final {
friend class FinalWrapper;
friend class Carrier<FinalWrapper>;
private:
Final() {}
Final(const Final &) {}
};
};
The EventFwd class is needed so that we have something sane to pass to the EventWrapper template as the derived class, so that the cast() static method will work. The FinalWrapper is there since in pre-C++11 we can't friend typecasts.
Now for the parametrized data carrier. It'd be the same as for the C++11 variant below except for needing to have a parametrized base class.
// A string carrier
template <typename Base> class StringData : public Base {
QString m_str;
public:
explicit StringData(const QString & str) : m_str(str) {}
QString value() const { return m_str; }
};
The C++11 MetaFactory
// The generic metafactory for unique event types that carry data
template <typename Derived, class Data> class EventMF {
class Final;
EventMF();
EventMF(const EventMF &);
~EventMF();
public:
class Event : public EventWrapper<Event>, public Data, private virtual Final {
public:
template<typename... Args>
Event(Args&&... args): Data(std::forward<Args>(args)...) {}
};
private:
class Final {
friend class Event;
private:
Final() {}
Final(const Final &) {}
};
};
The gymanstics with forward-declaration of the Final class are there since forward-declaring the Event class is more typing.
The data carrier is as simple as it gets:
// A string carrier
class StringData {
QString m_str;
public:
explicit StringData(const QString & str) : m_str(str) {}
QString value() const { return m_str; }
};
Usage & Tests (Common Code)
And now we can use the generic metafactory to make some concrete metafactories, and then to make the event classes we need. We create two unique event types that carry the data. Those event classes have unique staticType()s.
// A string event metafactory
template <typename Derived> class StringEventMF : public EventMF<Derived, StringData> {};
class Update : public EventMF<Update, StringData> {}; // using generic metafactory
class Clear : public StringEventMF<Clear> {}; // using specific metafactory
#if 0
// This should fail at compile time as such derivation would produce classes with
// duplicate event types. That's what the Final class was for in the matafactory.
class Error : public Update::Event { Error() : Update::Event("") {} };
#endif
int main(int, char**)
{
// Test that it works as expected.
Update::Event update("update");
Clear::Event clear("clear");
Q_ASSERT(Update::Event::staticType() != Clear::Event::staticType());
Q_ASSERT(Update::Event::staticType() == Update::Event::cast(&update)->staticType());
qDebug() << Update::Event::cast(&update)->value();
Q_ASSERT(Update::Event::cast(&clear) == 0);
qDebug() << Clear::Event::cast(&clear)->value();
Q_ASSERT(Clear::Event::cast(&update) == 0);
}

Add subclasses of templated base-class to container without super-base-class?

I'm trying to create a vector (or any STL container, really) that could hold a set of various objects that are subclasses of one specific type. The problem is that my base class is templated.
From what I can tell, I have to create an interface/abstract super base class (not sure what the preferred C++ terminology is). I'd prefer not to do this, and just use my (templated) abstract base class. Below is some example code.
Basically, is there a way not to require the WidgetInterface? Someway to tell the compiler to ignore template requirements? If I must have WidgetInterface, am I going the right way with the following?
#include <vector>
#include "stdio.h"
enum SomeEnum{
LOW = 0,
HIGH = 112358
};
// Would like to remove this WidgetInterface
class WidgetInterface{
public:
// have to define this so we can call it while iterating
// (would remove from Widget if ended up using this SuperWidget
// non-template baseclass method)
virtual void method() = 0;
};
template <class TDataType>
class AbstractWidget : public WidgetInterface{
public:
TDataType mData;
virtual void method() = 0;
// ... bunch of helper methods etc
};
class EnumWidget : public AbstractWidget<SomeEnum>{
public:
EnumWidget(){
mData = HIGH;
}
void method(){
printf("%d\n", mData); // sprintf for simplicity
}
};
class IntWidget : public AbstractWidget<int>{
public:
IntWidget(){
mData = -1;
}
void method(){
printf("%d\n", mData); // sprintf for simplicity
}
};
int main(){
// this compiles but isn't a workable solution, not generic enough
std::vector< AbstractWidget<int>* > widgets1;
// only way to do store abitary subclasses?
std::vector<WidgetInterface*> widgets2;
widgets2.push_back(new EnumWidget());
widgets2.push_back(new IntWidget());
for(std::vector<WidgetInterface*>::iterator iter = widgets2.begin();
iter != widgets2.end(); iter++){
(*iter)->method();
}
// This is what i'd _like_ to do, without needing WidgetInterface
// std::vector< AbstractWidget* > widgets3;
return 0;
}
No, you can't use directly AbstractWidget as a parameter of STL container or anything else.
The reason is that class AbstractWidget does not exist. It is only a template for compiler to construct classes from.
What exists is AbstractWidget<SomeEnum> and AbstractWidget<int> only because of EnumWidget and IntWidget inheriting from them.
Templates exist at compiler-level only. If AbstractWidget<T> weren't used anywhere in your code, there would be no traces of it during the runtime.
Therefore, the code you posted seems to be the best (if not only) solution for your problem.
What you've done is the solution: you need a common class/interface, and since AbstractWidget is class template, therefore it cannot be used as common class for all concrete classes for which the template argument is different. So I think, you should go with this class design. It seems to be quite reasonable solution.
In fact the classes AbstractWidget<int> and AbstractWidget<double> are different classes, so your class IntWidget is a subclass of the first but is in no relation with the second. You need to have a common parent class to put in the vector so unfortunately you can not avoid the common interface that is not templated.
This could be completely in the wrong direction, but could you do something like this:
template <class T>
class ConcreteWidget : public AbstractWidget<T>
{
};
and then use template specialization to define your specific widgets like this:
template <>
class ConcreteWidget : public AbstractWidget<int>
{
public:
ConcreteWidget() : mData(-1) {}
};
template <>
class ConcreteWidget : public AbstractWidget<SomeEnum>
{
public:
ConcreteWidget() : mData(HIGH) {}
};
So rather than having an IntWidget and an EnumWidget, you'd have a ConcreteWidget and ConcreteWidget and then could simply have a vector<WidgetInterface> that would be the super of all of these generic children?
I'm not sure if this solves your problem, or would even work. I'd love feedback on this answer.

Can we turn such structure into typed class/function?

So in structure like
struct RenderCastedDataFunctor
{
simpleRendererGraphElement* obj_;
RenderCastedDataFunctor(simpleRendererGraphElement* obj)
: obj_(obj) { }
void operator()(char* castedChar, int castedCharLength)
{
obj_->renderCastedData(castedChar, castedCharLength);
}
};
can we turn simpleRendererGraphElement* into abstract type and make its function name we use in structure (renderCastedData) abstract too?
So I have a function inside charGenerator class
template <typename Function>
void AddSubscriberToGeneratedData(Function f)
I want to pass to it functions from different classes of type void (differentClass::*)(char*, int)
With that structure inside some simpleRendererGraphElement I can subscribe function called renderCastedData to data with
charGenerator->AddSubscriberToGeneratedData(RenderCastedDataFunctor(this));
I want to have a way to be capable to pass abstract class function that takes char* and int to AddSubscriberToGeneratedData. How to do such thing?
can we turn
simpleRendererGraphElement* into
abstract type and make its function
name we use in structure
(renderCastedData) abstract too?
Very very good idea. You should do this. Make the class abstract by making it's functions virtual, and then define a concrete class (deriving from this abstract class) which implements the virtual functions. That would be a better design!
And the rest seems already fine. You don't have to do anything, as you're doing this:
AddSubscriberToGeneratedData(RenderCastedDataFunctor(this));
I suppose, here this represents the pointer to an instance of the concrete class. If so, then that should work!
EDIT:
I understand how good this Idea is but
I do not get how to implement it. that
is why I am asking.
Alright. Here is an example:
class AbstractGraphElement
{
public:
virtual void RenderCastedData(char* castedChar, int castedCharLength) = 0;
};
This is your abstract class, and RenderCastedData is a pure virtual function. Now you need to define a concrete class which must define RenderCastedData function. So here it is:
class SimpleGraphElement : public AbstractGraphElement
{
public:
virtual void RenderCastedData(char* castedChar, int castedCharLength)
{
//function body - define it yourself
}
};
Done!
Now what you need to do is this. Modify RenderCastedDataFunctor as follows:
struct RenderCastedDataFunctor
{
AbstractGraphElement* m_graphElement;
RenderCastedDataFunctor(AbstractGraphElement* graphElement)
: m_graphElement(graphElement) { }
void operator()(char* castedChar, int castedCharLength)
{
m_graphElement->RenderCastedData(castedChar, castedCharLength);
}
};
Then add subscriber,
AbstractGraphElement *pGraphElement = new SimpleGraphElement();
AddSubscriberToGeneratedData(RenderCastedDataFunctor(pGraphElement));
I think it gave your some idea, right? The important point is : use pointer of type AbstractGraphElement but initialize this pointer with SimpleGraphElement. I think, you should read about virtual functions, and runtime polymorphism. That would help you a lot.

Factory pattern and class templates in C++

I have a hierarchy of class templates. At the top of the hierarchy is an abstract base class (interface). I won't know which concrete implementation to instantiate until runtime, so it seems like the perfect situation to use the factory pattern. However, virtual member function templates are not allowed in C++.
How can I achieve a legal design similar to the below in C++?
The individual concrete implementations of the IProduct interface as well as the concrete factories will live in different dynamic libraries, one or more of which will be loaded at runtime.
template<class T> class IProduct
{
public:
virtual void doWork(const T & data) = 0;
};
template<class T> class ProductA : public IProduct<T> {/*...*/};
template<class T> class ProductB : public IProduct<T> {/*...*/};
class IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct() = 0;
};
class ProductAFactory: public IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct()
{
return new ProductA<T>;
}
};
class ProductBFactory: public IProductFactory
{
public:
template<class T> virtual IProduct<T> * createProduct()
{
return new ProductB<T>;
}
};
Why can't you templatize IProductFactory on T as well? That would get rid of your error, and it's no less general. The client is still going to have to know what T is in order to call thecreateProduct method.
Edit Re: comment
In order to do this, you will need to just create a templatized function to create the factory. So:
template<class T> IProductFactory<T>* getProductFactory();
Now your factory is templatized, the createProduct method is no longer a member template. Not sure what your criteria is for returning a ProductAFactory vs. a ProductBFactory but you will either have to pass in a string to choose, have this be a member function of another class that would make the decision, or have multiple free functions but only expose one version or another to a particular client.
This doesn't need a template. Does that eliminate your problem?