I have two classes which are inheriting from some virtual base class
class A : public BaseClass {
public:
static int foo(){ ... };
static void bar(){ ... };
};
class B : BaseClass {
public:
static int foo(){ ... };
static void bar(){ ... };
};
I have another class Worker
that is exposed to the client and makes use of these two classes
class Worker{
public:
static void doFoo(){
int result = A::foo();
...
}
static void doBar(){
A::bar();
}
}
I can either use A
in the Worker
class or B
. Right now, if I have to plug the class B
in Worker
class, I will have to make changes in all the functions in the Worker
.
class Worker{
public:
static void doFoo(){
int result = B::foo();
...
}
static void doBar(){
B::bar();
}
}
Is there a way I can keep the methods static, not create an object of either A
, B
, or the Worker
class and still be able to just make a few minor changes in the code and change the plug from A
to B
.
I thought of using templates (didn't explore it) but I don't want to let the user know of A
, or B
.
Thanks
You could make a class template like this:
template <typename T>
class Worker_T {
public:
static void doFoo(){
int result = T::foo();
}
static void doBar(){
T::bar();
}
};
and then to choose which class to actually use, you only have to choose one of the following:
using Worker = Worker_T<A>;
or
using Worker = Worker_T<B>;
and the user of Worker
doesn't need to know about A
or B
.