From cc6ca277e3d1f21c2e5e09626e6c9b0ab075cb1b Mon Sep 17 00:00:00 2001 From: "tomasz." Date: Fri, 2 Aug 2013 16:50:29 +0200 Subject: [PATCH] Added COROUTINE and DELEGATE class examples. --- include/tool/examples/Makefile | 9 ++++ include/tool/examples/coroutine_example.cpp | 48 +++++++++++++++++++++ include/tool/examples/delegate_example.cpp | 35 +++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 include/tool/examples/Makefile create mode 100644 include/tool/examples/coroutine_example.cpp create mode 100644 include/tool/examples/delegate_example.cpp diff --git a/include/tool/examples/Makefile b/include/tool/examples/Makefile new file mode 100644 index 0000000000..a605263689 --- /dev/null +++ b/include/tool/examples/Makefile @@ -0,0 +1,9 @@ +CXXFLAGS = -I../.. -I../../boost + +all: delegate_example coroutine_example + +delegate_example: delegate_example.cpp + g++ -o $@ $^ $(CXXFLAGS) + +coroutine_example: coroutine_example.cpp + g++ -o $@ $^ $(CXXFLAGS) -lboost_context \ No newline at end of file diff --git a/include/tool/examples/coroutine_example.cpp b/include/tool/examples/coroutine_example.cpp new file mode 100644 index 0000000000..b5ad730145 --- /dev/null +++ b/include/tool/examples/coroutine_example.cpp @@ -0,0 +1,48 @@ +#include +#include + +#include + +using namespace std; + +typedef COROUTINE MyCoroutine; + +class MyClass { + + public: + int CountTo(int n) + { + printf("%s: Coroutine says hi. I will count from 1 to %d and yield each value.\n", __FUNCTION__, n); + for(int i = 1; i <= n; i++) + { + printf("%s: Yielding %d\n", __FUNCTION__, i); + cofunc.Yield(i); + } + } + + void Run() + { + cofunc = MyCoroutine (this, &MyClass::CountTo); + printf("%s: Calling coroutine that will count from 1 to 5.\n", __FUNCTION__); + cofunc.Call(5); + while (cofunc.Running()) + { + printf("%s: Got value: %d\n", __FUNCTION__, cofunc.ReturnValue()); + cofunc.Resume(); + } + + printf("%s: Done!\n", __FUNCTION__); + } + + MyCoroutine cofunc; +}; + + +main() +{ + MyClass obj; + + obj.Run(); + + return 0; +} diff --git a/include/tool/examples/delegate_example.cpp b/include/tool/examples/delegate_example.cpp new file mode 100644 index 0000000000..2c872e72a5 --- /dev/null +++ b/include/tool/examples/delegate_example.cpp @@ -0,0 +1,35 @@ +#include +#include + +#include + +using namespace std; + +class MyClass { + + public: + int MyMethod(const string &arg) + { + printf("MyClass(this = %p)::MyMethod() called with string '%s', length %d\n", this, arg.c_str(), arg.length()); + return arg.length(); + } +}; + +typedef DELEGATE MyDelegate; + +main() +{ + MyClass t1; + MyClass t2; + + + MyDelegate ptr1 (&t1, &MyClass::MyMethod); + MyDelegate ptr2 (&t2, &MyClass::MyMethod); + + int retval1, retval2; + retval1 = ptr1("apples"); + retval2 = ptr2("cherries"); + + printf("Object 1 returned %d, object 2 returned %d\n", retval1, retval2); + return 0; +}