I have several methods which begin and end the same: file opening at the beginning, information collecting from the files prior to a specific treatment, file closing at the end... Pretty much like this:
1 2 3 4 5 6 7 8 9 10 11
A method
// Pre-operations
// Another method call
// Post-operations
A method 2
// Pre-operations
// Another method call 2
// Post-operations
...
Here is my question:
do I have to duplicate the code for each "Another method call i"
or can I pass the methods "Another method call i" to a common method M?
I'm not sure whether I can pass methods as arguments to other methods in C++ or not... Can I? How?
If it is possible, can you tell me how you would proceed with the following simplified example? I've put question marks ??? where I don't know what to code.
I don't think that my example is bad.
I just wanted to highlight the fact that the methods at stake may not have the same prototypes.
I made these methods simple so that no one would have to concentrate on what the methods actually do because this is not what I'm interested in.
More important: I do not see how to apply the "Functor" class you mentioned to this example.
Second: I have nothing against function pointers especially if they allow me to do what I want to do.
I just need a little help to understand how to use either one method or the other in that example.
> I just wanted to highlight the fact that the methods at stake may not have the same prototypes.
I didn't see that, sorry. However, if they have a different number of parameters ¿how do you expect to call them?
Variadic templates (c++0b) may solve that, didn't play with them so don't know.
Or just go with an standard prototype, letting the function to transform it
By instance void foo(void *data);
or using functors (not tested)
#include <iostream>
class bar{
public:
void print(int value){
std::cout << value << ' ';
}
};
class foo{
public:
typedefvoid ((bar::*method)(int)); //for sanity
void common(method m){
bar obj; //as it is a method, we need an object
(obj.*m)(42); //dereferencing the method pointer
}
};
int main(int argc, char **argv){
foo::method p = &bar::print; //choosing the method
foo test;
test.common(p);
return 0;
}
Sorry for the multiple post, I'm having some issues with the page/browser/javascript (don't know whom to blame)