Work on the answer
Basically, you get rid of all your classes, and instead you just use std :: function.
This generic function allows you to pass functions, lambda, functors and member functions (using std :: bind)
class Context { public: explicit Context(std::function<void()> input) : strategy(input) { } void run() { strategy(); } private: std::function<void()> strategy; };
Then you can pass any called to the context constructor:
Context ctx([] { std::cout << "Hello, world!\n"; }); ctx.run();
or
void sayHelloWorld(){ std::cout << "Hello, world!\n"; } int main(){ Context ctx( sayHelloWorld ); ctx.run(); }
or
class SayHelloWorld{ operator()(){std::cout << "Hello, world!\n";} } int main(){ SayHelloWorld hello_world; Context ctx( hello_world ); ctx.run(); }
source share