diff --git a/C++ Function.cpp b/C++ Function.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5369955be32530445b866596546efe35dbff2721 --- /dev/null +++ b/C++ Function.cpp @@ -0,0 +1,78 @@ +#include +#include +template +class base_func_wrapper +{ +public: + virtual TResult operator() (TArgs...) = 0; + virtual ~base_func_wrapper() {} +}; + +template +class func_pointer_wrapper final : public base_func_wrapper +{ +private: + using func_pointer = TResult (*) (TArgs...); + func_pointer p_; +public: + func_pointer_wrapper(func_pointer p):p_{p}{} + TResult operator() (TArgs...args) override { return p_(args...); } +}; + +template +class function_object_wrapper final : public base_func_wrapper +{ +private: + TFunc func_; +public: + template + function_object_wrapper(TFuncObj&& obj) : func_{ std::forward(obj) } {} + TResult operator() (TArgs...args) override { return func_(args...); } +}; + +template +class function; + +template +class function final +{ +private: + base_func_wrapper * func_ = nullptr; +public: + function(TResult(*p)(TArgs...)): func_{ new func_pointer_wrapper(p) }{} + + template + function(TFuncObj&& obj): func_ { new function_object_wrapper(std::forward(obj)) } {} + + ~function() { delete func_; } + function(const function&) = delete; + function& operator= (const function&) = delete; + + TResult operator () (TArgs...args) { return (*func_)(args...); } +}; + +int hello(int a,int b) +{ + return a + b; +} + +void hello2() +{ + std::cout<<"Hello"; +} + +int main() +{ + function f(hello); + std::cout< f2(hello2); + f2(); + + int i = 1,j = 2,k = 3; + function f3 = [i,j,k]{ + return i + j + k; + }; + std::cout<