From e970ef4dcd71688ca033bf414066647ebd1511cd Mon Sep 17 00:00:00 2001 From: Nanosonde <2073569+nanosonde@users.noreply.github.com> Date: Tue, 14 Jul 2020 13:25:16 +0200 Subject: [PATCH] Add simple alternative to std::function without smart pointers or move semantics --- examples/knx-linux/CMakeLists.txt | 1 + src/knx/simple_functional.h | 82 +++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/knx/simple_functional.h diff --git a/examples/knx-linux/CMakeLists.txt b/examples/knx-linux/CMakeLists.txt index 0e2d884..1b400f0 100644 --- a/examples/knx-linux/CMakeLists.txt +++ b/examples/knx-linux/CMakeLists.txt @@ -107,6 +107,7 @@ add_executable(knx-linux ../../src/knx/secure_application_layer.h ../../src/knx/security_interface_object.cpp ../../src/knx/security_interface_object.h + ../../src/knx/simple_functional.h ../../src/knx/simple_map.h ../../src/knx/table_object.cpp ../../src/knx/save_restore.h diff --git a/src/knx/simple_functional.h b/src/knx/simple_functional.h new file mode 100644 index 0000000..5f9724f --- /dev/null +++ b/src/knx/simple_functional.h @@ -0,0 +1,82 @@ +#pragma once +#include + +// +// Basis is https://shaharmike.com/cpp/naive-std-function/ +// +// Do not forget to call cleanup() once you do not need the function object (functor) anymore to free the memory. +// No move semantics and/or smart pointers are used + +template +class function; + +template +class function +{ + public: + function() + { + //printf("function()\n"); + callable_ = nullptr; + } + + ~function() + { + //printf("~function()\n"); + } + + template + function(T t) + { + //printf("function(T)\n"); + callable_ = new CallableT(t); + } + + template + function& operator=(T t) + { + //printf("operator=(T)\n"); + callable_ = new CallableT(t); + return *this; + } + + ReturnValue operator()(Args... args) const + { + //assert(callable_); + return callable_->Invoke(args...); + } + + void cleanup() + { + delete callable_; + } + + private: + class ICallable + { + public: + virtual ~ICallable() = default; + virtual ReturnValue Invoke(Args...) = 0; + }; + + template + class CallableT : public ICallable + { + public: + CallableT(const T& t) + : t_(t) { + } + + ~CallableT() override = default; + + ReturnValue Invoke(Args... args) override + { + return t_(args...); + } + + private: + T t_; + }; + + ICallable* callable_; +};