I am developing a project where I want it to be possible to specify which of several classes of methods/algorithms/functions is to be used. Each method "class" provides similar functions, and is interchangeable with the other classes.
I tried to implement this with a base abstract class with the method "classes" as derived classes:
class Method {
public:
virtual int function1(int) = 0;
virtual int function2(int, int) = 0;
};
class Method1 : public Method {
public:
int function1(int a) {
return a * 2;
}
int function2(int a, int b) {
return a + b;
}
};
class Method2 : public Method {
public:
int function1(int a) {
return a / 2;
}
int function2(int a, int b) {
return a - b;
}
};
void useMethod(int a, int b, Method& m) {
int result1 = m.function1(a);
int result2 = m.function2(a, b);
/* Do something with the results here */
}
int main() {
// Doesn't work, "type name is not allowed"
useMethod(1, 2, Method1);
useMethod(1, 2, Method2);
// Works, but seems unnecessary and less elegant
Method1 x;
useMethod(1, 2, x);
Method2 y;
useMethod(1, 2, y);
return 0;
}
The problem is that I can't seem to figure out how to allow using Method1
and Method2
without creating instances of them - which seems to me unnecessary, since they'll all just provide the same functions. Is there some way to make derived classes sort of "static" so they can be utilised without instances?