N
ngoonee
Hi all,
My intent is to code some algorith which repeatedly applies a certain
comparison function in C++. The algorithm itself works fine, but I'm
searching for easy ways to select the comparison function to be
applied, preferably at run-time (ie. no preprocessor defines).
A very simplified example of the idea I had:-
class baseclass {
private:
virtual int compare(int a,int b);
public:
int do_something(int a, int b) {
return compare(a,b);
}
};
class class2
ublic baseclass {
private:
int compare(int a,int b) {
return (b-a);
}
public:
};
class class1
ublic baseclass {
private:
int compare(int a,int b) {
return (a-b);
}
public:
};
Hence, if I create an instance of class1 and call the function
do_something, I'd like it to access the compare() function within
class1. Obviously, however, it doesn't work as is, meaning the method
I'm trying is not legal.
1. Could anyone suggest a legal way of doing what I'm trying to
accomplish, besides simply copy-pasting the whole code of
do_something() into a seperate class?
2. Is there any other way besides class inheritance to accomplish the
above?
Thank you all.
My intent is to code some algorith which repeatedly applies a certain
comparison function in C++. The algorithm itself works fine, but I'm
searching for easy ways to select the comparison function to be
applied, preferably at run-time (ie. no preprocessor defines).
A very simplified example of the idea I had:-
class baseclass {
private:
virtual int compare(int a,int b);
public:
int do_something(int a, int b) {
return compare(a,b);
}
};
class class2
private:
int compare(int a,int b) {
return (b-a);
}
public:
};
class class1
private:
int compare(int a,int b) {
return (a-b);
}
public:
};
Hence, if I create an instance of class1 and call the function
do_something, I'd like it to access the compare() function within
class1. Obviously, however, it doesn't work as is, meaning the method
I'm trying is not legal.
1. Could anyone suggest a legal way of doing what I'm trying to
accomplish, besides simply copy-pasting the whole code of
do_something() into a seperate class?
2. Is there any other way besides class inheritance to accomplish the
above?
Thank you all.