Reputation:
I want to have a function template inside a regular (non-template) class, which allocates a derived class with the needed parameters and returns a pointer to the base class:
class Factory {
public:
BaseClass_T * createObject(parameters) { return new Derived_T(parameters); }
};
So far I've only been using templates where parameters vary in type, but are always the same count. Since my different derived classes have different constructor signatures, I wonder if there is a way to template that and specify the generated function's parameter type and count via a template, something like this:
Factory f;
f.createObject<Derived1, void>(); // create createObject() for Derivev1() constructor
f.createObject<Derived2, int, double>(); // create createObject() for Derived2(int, double) constructor
Upvotes: 1
Views: 81
Reputation: 476970
You can use a variadic template:
#include <utility>
struct BaseClass_T { ~virtual BaseClass_T() = default; };
struct Factory
{
template <typename Der, typename ...Args>
BaseClass_T * create(Args &&... args)
{
return new Der(std::forward<Args>(args)...);
}
};
An even better design would be for your factory to return std::unique_ptr<BaseClass_T>
:
#include <memory>
struct SaneFactory
{
template <typename Der, typename ...Args>
std::unique_ptr<BaseClass_T> create(Args &&... args)
{
return std::make_unique<Der>(std::forward<Args>(args)...);
}
};
Upvotes: 1