#include #include #include template class Function { }; template class Function { public: Function() = default; template Function(T&& function) : impl { new Implementation{ std::forward(function) } } { } ~Function() { delete impl; } Ret operator()(Args... args) { return impl->perform(args...); } template Function& operator=(T&& function) { delete impl; impl = new Implementation{ std::forward(function) }; return *this; } private: class Base_Implementation { public: virtual ~Base_Implementation() = default; virtual Ret perform(Args... args) = 0; }; template class Implementation : public Base_Implementation { public: Implementation(T function) : function { function } { } Ret perform(Args... args) override { return function(args...); } private: T function; }; Base_Implementation* impl { 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; } }