I want to create something like a generic factory method - look at this:
template <class BaseType> class Factory { public: template <class ... Args> static BaseType* Create(const Args& ... args) { return new DerivedType(args ...); } };
Where DerivedType is another type derived from BaseType and defined elsewhere.
The problem is saving DerivedType . I want to do this, for example, as follows:
void f() { // Derived type may have more than one constructor, // that why I suggest using of the variadic templates. BaseType* ptr1 = Factory<BaseType>::Create("abc", 5, 10.); BaseType* ptr2 = Factory<BaseType>::Create(); ... } ... Factory<BaseType>::SetType<MyDerivedType>(); f(); Factory<BaseType>::SetType<YourDerivedType>(); f();
I can set different derived types, but they are all known at compile time. I can’t come up with a suitable technique for this.
Question: Can you advise one?
The rationale for this (thus the original problem, if someone suggests the question of whether this is an XY problem) is the ability to unit test some complex parts of the code. For example, if I have a code:
... Shuttle* shuttle1 = new ShuttleImpl("Discovery", Destination::Moon); Shuttle* shuttle2 = new ShuttleImpl(); ...
And I don’t want to really build the shuttle every time I run unit tests:
class Shuttle: public Factory<Shuttle> { ... } ... Shuttle* shuttle1 = Shuttle::Create("Discovery", Destination::Moon); Shuttle* shuttle2 = Shuttle::Create(); ...
So, in the unit test, I can just do: Shuttle::SetType<TestShuttle>(); .
There may be more “testable” classes, so for them I need a universal factory:
class Car: public Factory<Car> { ... } class Driver: public Factory<Driver> { ... } ...