There are two different algorithms being used throughout the code. Which one is chosen is determined at runtime by a parameter (e.g. true or false). I do not want to use if-statements each time the algorithm comes up.
So instead of writing the following every time
if (parameter==true)
algorithmOne();
else
algorithmTwo();
I want to set the algorithm at the beginning, like
if (parameter==true)
algorithm()=algorithmOne();
else
algorithm()=algorithmTwo();
and only use 'algorithm()' from this point forward.
How can I choose the algorithm at the beginning depending on a parameter after the code is already compiled?
Edit: How do you do that within the constructor of a class (since a pointer-to-member function is no regular pointer)? As both algorithms rely on member variables and functions of this class, it is inconvenient to derive a new class.
Solution: This could be solved with a virtual function and derived classes.
class Base
{
public:
Base();
virtual void algorithm() = 0;
~Base();
protected:
double d;
int i;
...
}
class DerivedOne : public Base
{
public:
DerivedOne() : Noise() {};
void algorithm() override;
~DerivedOne();
};
Base *b;
if (parameter==true)
{
b = new DerivedOne();
}
else
{
b = new DerivedTwo();
}
Then the function can be called with:
b->algorithm();
And deleted with:
delete b;
This may not be the best way but it seems to work for me. See answers and comments.