#include #include #include template class Function { }; template class Function { public: Function() = default; template Function(T&& callback) : storage { new Callable{ std::forward(callback) } } { } ~Function() { delete storage; } Ret operator()(Args... args) { return storage->call(args...); } template Function& operator=(T&& callback) { delete storage; storage = new Callable{ std::forward(callback) }; return *this; } private: class Callable_Base { public: virtual ~Callable_Base() = default; virtual Ret call(Args... args) = 0; }; template class Callable : public Callable_Base { public: Callable(T&& callback) : callback { std::forward(callback) } { } Ret call(Args... args) override { return callback(args...); } private: T callback; }; Callable_Base* storage { nullptr }; }; void test() { std::cout << "Function call!" << std::endl; } int add(int a, int b) { return a + b; } struct Test { void operator()() { std::cout << "Function object call!" << std::endl; } }; struct Multiply { int operator()(int a, int b) { return a * b; } }; int main() { std::cout << "==== Testcase 1: void() ====" << std::endl; { Function fun { test }; fun(); fun = Test{}; fun(); int x { 5 }; fun = [&x]() { std::cout << "x = " << x << std::endl; }; fun(); } std::cout << "==== Testcase 2: int(int, int) ====" << std::endl; { Function fun; fun = add; std::cout << "3 + 5 = " << fun(3, 5) << std::endl; fun = [](int a, int b) { return a - b; }; std::cout << "11 - 5 = " << fun(11, 5) << std::endl; fun = Multiply{}; std::cout << "7 * 4 = " << fun(7, 4) << std::endl; } }