For a homework, we need to modify a variety of images with multiple different algorithms and format a document with our answers. I have already coded the algorithms in C++, but I want to write a program that will modify the images and format the document automatically. To do this, I want to have a class of the form
class A
{
void f1(Image img)
{
// do something to the image
}
void f2(Image img)
{
// do something else to the image
}
public:
void setFunction(bool choice)
{
if(choice)
{
// define this.operator() = f1
}
else
{
// define this.operator() = f2
}
}
}
The reason I want to do this is because the homework requires us to compute different properties for the images, but most of the properties are repeated accross questions. Therefore, I want to write a single function of the form
void answerQuestion(Image img, A imgProcessor)
{
// load img, call imgProcessor(img)
// and get the necessary properties from
// img to answer the questions
}
This way, I can just do something like imgProcessor.setFunction(choice)
before passing the imgProcessor
object to answerQuestion
. I want to use an object because questions are split into several parts, so I would like the imgProcessor
object to hold on to some information required for the rest of the problem.
I don't know how to dynamically define or redefine the operator()
method, or if it is even possible. Of course, I am indifferent between overloading the call operator or just declaring my own method, but I want to be able to use this call in the same way accross the code. Is this possible in C++?
You'll have to somehow remember the choice. In C++, function pointers and function objects don't participate in overload resolution so you cannot actually replace operator()()
with a different function, but you certainly can write operator()()
with some type of conditional that checks the choice selected earlier and decides which function to call.