G
Guest
I have a rather newbie question regarding design of class hierarchy.
Suppose I have a class Class0, and need to implement a public
Class0.compute() interface. There are three different ways to choose
the implementation, and the user of the class has to be able to make
that choice. Here is what I have in mind. I declare three classes,
ClassA, ClassB, ClassC, and each of them has a distinct compute()
method that can be used by Class0. Class0 is a template class, as
follows:
template <class T>
class Class0 {
public:
double compute() { return p->compute(); }
private:
T *p;
};
Then I could do:
Class0<ClassA> C;
C.compute();
Problem: classA.compute(), classB.compute() and classC.compute() all
have different number and types of parameters. I might also want to
add classD, etc. in the future. This means I would need to implement
three different compute() functions in the public area of Class0.
Alternatively, I could write a method in Class0 that returns a
corresponding compute() function from the pointer p, but this doesn't
seem elegant.
Another idea I have is to declare Class0 a descendant of Class{A,B,C}:
template<class T>
class Class0 : public T {
....
}
and then
Class0<classA> C;
Then Class0 will inherit compute() from classes ClassA, etc.
What makes me uncomfortable is that Class0 and classes Class{A,B,C}
do not really have "is-a" relationship. A,B,C only provide the means
to do certain computations.
Any better way to accomplish what I am trying to do?
Many thanks,
Suppose I have a class Class0, and need to implement a public
Class0.compute() interface. There are three different ways to choose
the implementation, and the user of the class has to be able to make
that choice. Here is what I have in mind. I declare three classes,
ClassA, ClassB, ClassC, and each of them has a distinct compute()
method that can be used by Class0. Class0 is a template class, as
follows:
template <class T>
class Class0 {
public:
double compute() { return p->compute(); }
private:
T *p;
};
Then I could do:
Class0<ClassA> C;
C.compute();
Problem: classA.compute(), classB.compute() and classC.compute() all
have different number and types of parameters. I might also want to
add classD, etc. in the future. This means I would need to implement
three different compute() functions in the public area of Class0.
Alternatively, I could write a method in Class0 that returns a
corresponding compute() function from the pointer p, but this doesn't
seem elegant.
Another idea I have is to declare Class0 a descendant of Class{A,B,C}:
template<class T>
class Class0 : public T {
....
}
and then
Class0<classA> C;
Then Class0 will inherit compute() from classes ClassA, etc.
What makes me uncomfortable is that Class0 and classes Class{A,B,C}
do not really have "is-a" relationship. A,B,C only provide the means
to do certain computations.
Any better way to accomplish what I am trying to do?
Many thanks,