In c++ you can achieve this using run time polymorphism, i.e. defining an abstract base class and deriving concrete classes from it.
For example, in a XXXX
class, declare a Sum
method as pure virtual, and every classes inheriting from it have to implement that method (otherwise they stay abstract as well):
The base class:
class XXXX
{
public:
virtual ~XXXX() = default;
virtual bool Sum() = 0; //this has to be overridden
};
A derived class:
class XXXX_1 : public XXXX
{
public:
bool Sum() override
{
// Sum implementation here
}
};
The Sum
implementation is specific of the XXXX_1
class. You can have more implementations, but a different class (derived from XXXX
) is needed for each of them.
A more sophisticated pattern, which doesn't involve polymorphism at all:
typedef bool (*_Sum)(); // _Sum is now a function type
class XXXX
{
_Sum _sum;
public:
XXXX(_Sum s) : _sum(s){}
bool Sum()
{
if(_sum != nullptr)
{
return _sum();
}
return false; //just a default
}
};
When instantiating the above class, a function pointer is passed in construction, the Sum
method will execute the passed in function and return its return value:
bool f() //this function matches the _Sum type defined above
{
return false;
}
int main(int argc, char *argv[])
{
XXXX xxxx(f); //we're passing a pointer to f function, here
xxxx.Sum(); //execute f
return 0;
}
Using templates, things can get even more generic:
template <typename F>
class XXXX
{
F _f;
public:
XXXX(F f) : _f(f){}
bool f()
{
return _f();
}
};
In the above class, the template parameter is now a function type, and the member function f
has its same return type.
We can pass the _Sum
function type defined above as F
, and (in construction) a pointer to the function f
defined above:
int main(int argc, char *argv[])
{
XXXX<_Sum> xxxx(f);
xxxx.f(); //execute f again
return 0;
}
or whatever function of whatever type:
#include <iostream>
typedef void (*_Void)(); //another function type
void v(){ std::cout << "Hello" << std::endl; }
int main(int argc, char *argv[])
{
XXXX<_Void> xxxx(v);
xxxx.f();
return 0;
}