Define virtual function to be pure in special cases of templated class - c++

I am trying to define a templated base class that defines a virtual interface to be overriden by the user. In some cases it would make sense to have a default implementation of this method but that isn't true for all type parameters. Consider this:
template<typename T>
struct supplier
{
virtual std::unique_ptr<T> supply(std::istream& moreData) = 0;
};
Now I want to offer the following default implementation given that T is default constructible (std::is_default_constructible):
std::unique_ptr<T> supply(std::istream& moreData)
{
return std::unique_ptr<T>(new T);
}
The problem is not how to define this function for appropriate T but how to make it appear as a pure virtual function - and thus force an implementation by the user - when it's not defined and like a normal virtual function, if it is.
I think I'm just missing some obvious solution. I tried to specialize struct supplier but that means I'd have to define the rest of the interface two times, so it's definitly not a scaling solution. It also means that I have to provide the rest of the interface two times.
Is there an affordable solution for a rich base class with many virtual functions that may either offer an implementation or be purely virtual?

Extract the part you need to specialize into a separate class template, and then inherit from it.
namespace details {
template<class T, bool = std::is_default_constructible<T>::value>
struct supplier_base
{
virtual std::unique_ptr<T> supply(std::istream& moreData) = 0;
};
template<class T>
struct supplier_base<T, true>
{
virtual std::unique_ptr<T> supply(std::istream& moreData)
{
return std::unique_ptr<T>(new T);
}
};
}
template<class T>
struct supplier : details::supplier_base<T> { /* ... */ };

Related

C++20 Concept for checking presence of private class members

Consider the situation of having some class A together with a factory class Factory. A is supposed to have only private constructors (to prevent the user from creating such an object), and is friends with Factory, who can then construct Objects of type A.
A also has some private attribute which cannot be set in in A's constructor (because the value is not known yet), but will be computed by Factory and then set correctly before A is returned.
Now i have the situation that I have similar classes B,C, ... to A that should also be constructed by Factory, which will thus be a template.
So the situation is currently
template<typename T>
class Factory {
public:
T get() {
T t;
void* computed_value = nullptr; // suppose we compute a
t._value = computed_value;
return t;
}
};
class A {
// Some public methods for the user
friend class Factory<A>;
private:
A() : _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// some more attributes that will correctly be initialsed by the default constructor
};
class B {
//Some public methods for the user
friend class Factory<B>;
private:
B(): _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// Some more attributes that will correctly be initialised by the default constructor
};
void foo() {
Factory<A> a_factory;
A a_elem = a_factory.get();
Factory<B> b_factory;
B b_elem = b_factory.get();
}
Actually, an instance of Factory<A> also stores some values that are used in the construction of some A, that are set by the constructor of Factory, this is why i use instances of the Factory and not static methods.
Now comes the point: I would like to use Concepts in order to constrain the template<typename T> that is used by the Factory, so something like:
template<typename T>
concept Factorable = requires (T t) {
std::same_as<void*, decltype(t._value)>;
};
template<Factorable t>
class Factory { //...
As expected, this does not work, because the corresponding required expressions are private and thus not available, Factorable<A> will just be false.
Now, hanging the attribute and constructor of class A to public will thus lead to a nice generic Factory and the below (correct) code
template<Factorable T>
class Factory {
public:
T get() {
T t;
void* computed_value = nullptr; // suppose we compute a
t._value = computed_value;
return t;
}
};
class A {
// Some public methods for the user
template<Factorable T>
friend class Factory;
public:
A() : _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// some more attributes that will correctly be initialsed by the default constructor
};
class B {
//Some public methods for the user
template<Factorable T>
friend class Factory;
public:
B(): _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// Some more attributes that will correctly be initialised by the default constructor
};
void use() {
Factory<A> a_factory;
A a_elem = a_factory.get();
Factory<B> b_factory;
B b_elem = b_factory.get();
}
Note the subtlety that we now had to declare all generic variants of Factory as a friend of classes A and B, since Factory<A> cannot be evaluated while defining class A itself and thus not explicitly declared as a friend. I am however fine with this, since in the implementation of the Factory<T> we will not access other classes than T anyways (It would however be nice to achieve a friend class Factory<A>, but this is not my priority).
But this approach leads to the massive problem that a user can now generate instances of A by just calling its constructor, which just sets _value = nullptr, so we get 'invalid' instances of A that may lead to undefined behaviour etc. So this is really not the way to go for, although the use of the concepts in above expression would be nice.
So my question now is:
How can I achieve both of the above, in order have private constructors and attributes, but still use concepts
I found out that concepts are actually context-sensitive, in the sense that the required expressions are checked in the invoking context, so in fact the following code will correctly compile
template<typename T>
concept Factorable = requires (T t) {
std::same_as<void*, decltype(t._value)>;
};
template<typename T>
class Factory {
static_assert(Factorable<T>);
public:
T get() {
T t;
void* computed_value = nullptr; // suppose we compute a
t._value = computed_value;
return t;
}
};
class A {
// Some public methods for the user
template<typename T>
friend class Factory;
private:
A() : _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// some more attributes that will correctly be initialsed by the default constructor
};
class B {
//Some public methods for the user
template<typename T>
friend class Factory;
private:
B(): _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// Some more attributes that will correctly be initialised by the default constructor
};
void use() {
Factory<A> a_factory;
A a_elem = a_factory.get();
Factory<B> b_factory;
B b_elem = b_factory.get();
}
since now the compiler will first accept any typename T as generic and then check the concept for the given T within the context of the class, which will thus evaluate to true, since Factory is friends with both A and thus has access to its data members.
So this approach can actually guarantee user-safe instantiation of class A and throwing corresponding errors when the static_assertion fails to evaluate, but of course this is not the way a concept is intended to use, since then we basically just fall back to duck-typing as it was before the introduction of concepts and manually assert certain things, which loses the desired properties of concepts (late error throwing etc., but also losing IDE completion).
A solution would of course be to have the possibility to require the presence of private attributes in a concept, something like the following
//Suppose the existence of a function like std::ignore_private(expression)
template<typename T>
concept Factorable = requires (T t) {
std::same_as<void*, decltype(std::ignore_private(t._value))>;
}
where std::ignore_private is of course completely made up (and i also don't know what syntax it actually should have), but you get the point what i actually want.
So, is there any way to express something like this in a concept?
At least, i could imagine that, since checking for private attributes is a constexpr and can also be checked at compile time.
If you don't find a better solution a compromise could be to constrain the method:
template<typename T>
class Factory {
public:
T get() requires Factorable<T>
{
// ...
}
};
After experimenting around a while, i came up with the following workaround, using an additional Tester class, that has to be declared friend by A:
template<typename T>
concept PrivateFactorable = requires (T t) {
std::same_as<void*, decltype(t._value)>;
};
template<typename T> class Tester {
public:
constexpr static bool factorable = PrivateFactorable<T>;
};
template<typename T>
concept Factorable = Tester<T>::factorable;
template<Factorable T>
class Factory {
public:
T get() {
T t;
void* computed_value = nullptr; // suppose we compute a meaningful value here
t._value = computed_value;
return t;
}
};
class A {
// Some public methods for the user
template<Factorable T>
friend class Factory;
friend class Tester<A>;
public:
A() : _value(nullptr) {} //initialised with nullptr since we have no meaningful value (yet)
void* _value;
// some more attributes that will correctly be initialsed by the default constructor
};
This will correctly redirect Factorable<A> into the tester class, who can evaluate the concept withing friend context with A. The only downside is that A has to have yet another friend (and we get some more concepts in the background), but this seems okay
First, I think it’s a compiler bug if the value of a concept depends on the lexical location of requesting it.
It could interfere with subsumption where that matters, but you can write the constraint directly:
template<class T> requires std::same_as<void*, decltype(T::_value)>
class Factory {…};
Substitution failures in a constraint cause it to be unsatisfied whether it’s in a concept or not.

How can I implement the visitor patter with return type in C++

I want to implement the visitor pattern for one of my class without having to depend on the types that will implement the interface to visit them.
My solution was this:
class model::VisitableNode {
public:
template<class T>
virtual T accept(NodeVisitor<T>);
}
But C++ says that it doesn't support template + virtual methods
Node in my application will have only one implementation but if I don't use a template return type my model class will depend on the toolkit that I'm using to create the graphic for my app.
If a visitor needs to return a value, it is normal to store the returned value in the visitor itself. Thus:
NodeVisitor<double> dv;
node->accept(dv);
double result = dv.result();
If you don't like the boilerplate, you can wrap it in a non-virtual member:
class model::VisitableNode {
public:
template<class T>
/* non-virtual */ T accept(NodeVisitor<T>& v) {
do_accept(v);
return v.result;
}
virtual void do_accept(NodeVisitorBase& v) = 0;
}
Why not template the class itself?
template<class T>
class model::VisitableNode<T> {
public:
virtual T accept(NodeVisitor<T>);
}

Iterate over class inheritances in C++

Assume I have a some classes architecture (the number of the classes is growing up during the development time), that each class inherit from N classes with the same basic interface. What is the best way (if possible) to create a base function (in the base class OR in the derived class) that will iterate over the inheritances?
Target: Avoid developers mistakes and make sure we won't forget to call all the base functions from all of the inheritances & make the code more clear to read and understandable.
Please see edit notes for updated state
Short Example:
class shared_base {
public:
virtual void func() = 0;
}
class base_1 : virtual public shared_base {
public:
void func() override {}
}
class base_2 : virtual public shared_base {
public:
void func() override {}
}
class target : virtual public base_1, virtual public base_2 {
public:
void func() override {
// Instead of:
base_1::func();
base_2::func();
// ... My func() implementation
/*
~~TODO~~
for_each(std::begin(inheritances), std::end(inheritances), [](auto& inheritance) -> void { inheritance::func(); })
~~TODO~~
*/
}
}
More descriptive & practical example:
class base {
public:
virtual void func() = 0;
/*...Some interface (pure virtual) functions...*/
}
class base_core : virtual public base {
public:
void func() override {}
/*...Some base implementations for the rest...*/
protected:
template <typename FuncT>
virtual void iterate_over_base_core_inheritances(FuncT function_to_apply) {
/*~~TODO~~*/
}
}
template <class Decorator = base_core, typename = typename std::enable_if<std::is_base_of<base_core, Decorator>::value>::type>
class core_1 : virtual public Decorator {
public:
void func() override {
// Will iterate (once) over Decorator
/*iterate_over_base_core_inheritances([](core_base*) -> void {
// Implementation
});*/
// Instead of:
Decorator::func();
}
/*More functions implementations*/
}
template <class Decorator = base_core, typename = typename std::enable_if<std::is_base_of<base_core, Decorator>::value>::type>
class core_2 : virtual public core_1<>, virtual public Decorator {
public:
void func() override {
// Will iterate (twice) over core_1 and Decorator
/*iterate_over_base_core_inheritances([](core_base*) -> void {
// Implementation
});*/
// Instead of:
Decorator::func();
core_1::func();
//... Self func() implementation
}
/*More functions implementations*/
protected:
// If it's not possible doing it in the upper hierarchy level is it possible do it here?
template <typename FuncT>
void iterate_over_base_core_inheritances(FuncT function_to_apply) override {
/*~~TODO~~*/
}
}
Some things to know:
I am working on Linux 64x platform (Ubuntu 16.04)- if it's matter for the answers.
The idea behind this code is to create kind of Decorator DP, which will be easy to extend and to understand, and also will enable the developers to use the protected functions/attributes of the base class.
A practical example (for my actual use) can be found in this commit.
Edit:
Thanks to #RaymondChen I got a working solution, with (so far) only one minor issue: Every time I want to use a class that implemented this way, I need to specify the core_base class in it's template arguments list (before- I was using the default type parameter). I am looking for a way to solve this issue.
The current solution:
template <class ...Decorators>
class core_2 : virtual public Decorators... {
public:
static_assert((std::is_base_of<base_core, Decorators>::value && ...), "All decorators must inherit from base_core class.");
void func() override {
(Decorators::func(), ...);
//... Self func() implementation
}
/*More functions implementations*/
}
Creating an instance example:
Current:
std::shared_ptr<base> base = std::make_shared<core_2<core_1<base_core>, core_3<base_core>>>();
Desired:
std::shared_ptr<base> base = std::make_shared<core_2<core_1<>, core_3<>>>();
A practical example (for my actual use) can be found in this commit.
Thanks to #RaymondChen I got really close to my original target with the following solution [See update section at the bottom]:
template <class ...Decorators>
class core_2 : virtual public Decorators... {
public:
static_assert((std::is_base_of<base_core, Decorators>::value && ...), "All decorators must inherit from base_core class.");
void func() override {
(Decorators::func(), ...);
//... Self func() implementation
}
/*More functions implementations*/
}
Explanation:
Using parameters pack we can create a "list" of classes we inherit from, and using folding expression [c++17] we can implement it in just few lines of code.
Pros compare to my original idea:
The object creation line is more clear and logically now:
Before:std::shared_ptr<base> base = std::make_shared<core_2<core_1<core_3<>>>>();
After:std::shared_ptr<base> base = std::make_shared<core_2<core_1<base_core>, core_3<base_core>>>();
Because core_1 & core_3 are independent, but core_2 is using both of them.
No need of new function in the base/derived class, it's just fit within the target line (for example in is_equal function that didn't mention within this post).
Lost functionality:
Template validation of is_base_of (Solved with static_assert & fold expressions).
Default inheritance in case that no inheritance specified is not possible yet (Still trying to solve).
Current:
std::shared_ptr<base> base = std::make_shared<core_2<core_1<base_core>, core_3<base_core>>>();
Desired:
std::shared_ptr<base> base = std::make_shared<core_2<core_1<>, core_3<>>>();
Update
After a lot of research and tries, I came up with the following solution (improved also with C++20 concepts feature):
template <class T>
concept Decorator = std::is_base_of_v<base_core, T>;
class empty_inheritance {};
template<typename Base = base_core, typename ...Decorators>
struct base_if_not_exists {
static constexpr bool value = sizeof...(Decorators);
using type = typename std::conditional<value, empty_inheritance, Base>::type;
};
template <Decorator ...Decorators>
class core_2 : virtual public base_if_not_exists<base_core, Decorators...>::type, virtual public Decorators... {
public:
void func() override {
if constexpr (!base_if_not_exists<base_core, Decorators...>::value) {
base_core::func();
}
(Decorators::func(), ...);
//... Self func() implementation
}
/*More functions implementations*/
}
No functionality lost :)

Mapping runtime types to a parallel class hierarchy … with templates

I have two class hierarchies which have a 1:1 relationship: some normal classes A, B which have a common Root interface, and a WrapperRoot<T> interface with two concrete instantiations WrapperA<T> and WrapperB<T>. I am now looking to implement a function auto wrap<T>(Root& elem) -> unique_ptr<WrapperRoot<T>> that maps each normal class to its wrapper class.
The exact type of the wrappers is important as they will have virtual methods, and the exact type of the Root objects is not statically known.
Attempted solutions
My first idea was to declare a template virtual method in Root:
class Root {
...
public:
template<typename T>
virtual auto wrap() -> unique_ptr<WrapperRoot<T>> = 0;
}
which could then be implemented in the child classes as
class A : public Root {
...
template<typename T>
virtual auto wrap() -> unique_ptr<WrapperRoot<T>> override {
return make_unique<WrapperA<T>>();
}
}
As I was to find out, C++ does not allow templates for virtual methods. I did some further research and found the technique of type erasure, which allows us to break through this virtual vs. template dichtomy. Perhaps it might be possible to have each class select their wrapper type by passing in a visitor-like object that has erased the template parameter <T>? However, I am still fairly new to C++, and all my attempts to implement this have only moved the problem into another level, but not solved them.
This is especially frustrating since other languages which I am familiar with have no problem expressing this structure. E.g. in Java it is no problem to define a virtual method <T> WrapperRoot<T> wrap() { return new WrapperA<T>(); }, but that is because Java implements templates via reinterpreting casts. Java's implementation would be phrased in C++ as:
template<typename T>
WrapperRoot<T>* wrap() { return reinterpret_cast<WrapperRoot<T>*>(wrapper_impl()); }
virtual void* wrapper_impl() { return new WrapperA<void*>() }
However, I would like to work with the C++ type system rather than violating it by casting void pointers around.
Test Case
To phrase my problem unambiguously, I have created the below test case. Once wrap is implemented correctly, it should output this:
WrapperA
WrapperB
The main method should not be modified, but arbitrary methods, helper types, and an implementation for the wrap function may be added.
#include <iostream>
#include <memory>
using namespace std;
// the Root hierarchy
class Root {
public:
virtual ~Root() {}
};
class A : public Root {};
class B : public Root {};
// the Wrapper hierarchy
template<typename T>
class WrapperRoot {
public:
virtual ~WrapperRoot() {}
virtual T name() = 0;
};
template<typename T>
class WrapperA : public WrapperRoot<T> {
public:
virtual T name() { return T("WrapperA\n"); }
};
template<typename T>
class WrapperB : public WrapperRoot<T> {
public:
virtual T name() { return T("WrapperB\n"); }
};
// the "wrap" function I want to implement
template<typename T>
auto wrap(Root& ) -> unique_ptr<WrapperRoot<T>>;
// util
template<typename T, typename... Args>
auto make_unique(Args... args) -> unique_ptr<T> {
return unique_ptr<T>(new T(forward<Args>(args)...));
}
int main() {
unique_ptr<Root> a = make_unique<A>();
unique_ptr<Root> b = make_unique<B>();
cout << wrap<string>(*a)->name()
<< wrap<string>(*b)->name();
}
How can I make this work? Or do I need to resort to type-violating hacks?
The simplest way to get this to work would just be dynamic_casting the Root& to work out what the runtime type of it is:
template<typename T>
auto wrap(Root& root) -> unique_ptr<WrapperRoot<T>>
{
if (dynamic_cast<A*>(&root)) {
//root is an A, return a WrapperA
return make_unique<WrapperA<T>>();
}
else if (dynamic_cast<B*>(&root)) {
//root is a B, return a WrapperB
return make_unique<WrapperB<T>>();
}
throw std::runtime_error("No wrapper for that type");
}
Demo
As it turns out, this can be solved with type erasure, the Visitor Pattern, and a bit of indirection. The solution is clean, and does not require us to re-implement dynamic dispatch inside the wrap function.
The core idea is to introduce a WrapperSelector visitor interface:
class WrapperSelector {
public:
virtual auto visit(A&) -> void = 0;
virtual auto visit(B&) -> void = 0;
};
The Root hierarchy needs to be modified a bit to accept this visitor, and to perform the double dispatch:
class Root {
public:
virtual ~Root() {}
virtual auto accept(WrapperSelector&) -> void = 0;
};
class A : public Root {
public:
virtual auto accept(WrapperSelector& wrapper) -> void {
wrapper.visit(*this);
}
};
class B : public Root {
public:
virtual auto accept(WrapperSelector& wrapper) -> void {
wrapper.visit(*this);
}
};
So far, this is the bog-standard Visitor Pattern in C++. What we now do is introduce a templated class WrapperSelectorImpl<T> : public WrapperSelector. Since it is templated but only used through the un-templated interface, this implements type erasure. Internally, we construct this WrapperSelectorImpl as a container for a borrowed WrapperRoot<T> pointer, into which we write the selected wrapper. After the accept/visit sequence has ended, that pointer will be filled with the wrapper, so no virtual method needs to return a template-parameterized type. Also, the accept method does nothing but select the corresponding visit method, so the types in the Root hierarchy don't need to know about the WrapperRoot hierarchy – a concrete WrapperSelector will handle this mapping.
template<typename T>
class WrapperSelectorImpl : public WrapperSelector {
unique_ptr<WrapperRoot<T>>& _wrapper;
public:
explicit WrapperSelectorImpl(unique_ptr<WrapperRoot<T>>& wrapper)
: _wrapper(wrapper)
{}
virtual auto visit(A&) -> void override {
_wrapper = make_unique<WrapperA<T>>();
}
virtual auto visit(B&) -> void override {
_wrapper = make_unique<WrapperB<T>>();
}
};
Our wrap function must now set up a pointer, a WrapperSelectorImpl which borrows that pointer, let the given object in the Root hierarchy select the wrapper through the WrapperSelector, and return the now-populated pointer:
template<typename T>
auto wrap(Root& obj) -> unique_ptr<WrapperRoot<T>> {
unique_ptr<WrapperRoot<T>> wrapper;
WrapperSelectorImpl<T> wrapper_selector(wrapper);
obj.accept(wrapper_selector);
return wrapper;
}
Generalization
The above technique can be used to implement arbitrary templated virtual methods, or the visitor pattern with arbitrary return types. The prerequisites for this is minimal support for the Visitor Pattern`:
some Subject class or class hierarchy with a virtual void accept(SubjectVisitor& v) { v.visit(*this); }.
some SubjectVisitor interface with virtual void visit(S&) = 0 methods for each class S in the Subject class hierarchy.
Now assume we wish to implement a method with the following pseudo-signature in the Subject hierarchy:
class Subject {
...
template<typename R, typename T, typename... Args>
virtual R frobnicate(Args... args) = 0;
}
We can then use the following steps to implement this:
First, we create a wrapper function that exposes the public interface of our dispatching logic. This might be a non-virtual templated method in Subject, or a free function. The internals are the same as in the above example: Set-up of the return value, set-up of the visitor (borrowing a reference to the return value), doing the dispatch, and returning the value.
Since this is so general, we can pack this into a reusable templated function:
// most general implementation
template<typename ReturnType, typename Subject, typename Visitor, typename... Args>
auto manage_visitor(Subject& subject, Args... args) -> ReturnType {
ReturnType return_value;
Visitor visitor(return_value, std::forward(args)...);
subject.accept(visitor);
return return_value;
}
class Subject {
...
template<typename R, typename T, typename... Args>
R frobnicate(Args... args) {
return manage_visitor<R, Subject, ConcreteSubjectVisitor<R, T>>(*this, std::forward(args)...);
}
};
Note that this assumes the return value to be default-constructible. If this is not the case, substituting unique_ptr<ReturnType> for ReturnType could be a solution.
We now have to provide a class ConcreteSubjectVisitor : public SubjectVisitor that provides the actual implementation.
template<typename ReturnType, typename T>
class ConcreteSubjectVisitor : public SubjectVisitor {
ReturnType& return_value;
ArgType something;
public:
ConcreteSubjectVisitor(ReturnType& ret, ArgType& other_arg) : return_value(ret), something(other_arg) {}
virtual void visit(S1&) override { ... }
virtual void visit(S2&) override { ... }
...
};
The only thing which matters is that it can write to the return value. Note that the visitor can take additional arguments through the constructor, which makes it somewhat related to the std::bind function or to constructing a lambda. The visit definitions then contain the actual code, which has access to all type parameters of the visitor, and all constructor arguments of the visitor.
Open problems:
handling of return types that are not default-constructible (pointers or custom defaults)
specialization for void return type (problem decays to “normal” visitor pattern)
generalization to full multi-methods (trivial if method is in curried form)
providing a convenient interface
const-correctness (must be applied on a per-visitor basis, Subject::accept can be provided as const and non-const).

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?