Squashed 'third_party/autocxx/' content from commit 629e8fa53
git-subtree-dir: third_party/autocxx
git-subtree-split: 629e8fa531a633164c0b52e2a3cab536d4cd0849
Signed-off-by: Brian Silverman <bsilver16384@gmail.com>
Change-Id: I62a03b0049f49adf029e0204639cdb5468dde1a1
diff --git a/examples/subclass/src/messages.cc b/examples/subclass/src/messages.cc
new file mode 100644
index 0000000..4d24aab
--- /dev/null
+++ b/examples/subclass/src/messages.cc
@@ -0,0 +1,70 @@
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This example shows Rust subclasses of C++ classes.
+// See messages.h and main.rs for most of the interesting code.
+
+#include "messages.h"
+#include <ctime>
+#include <iostream>
+#include <sstream>
+#include <vector>
+#include <functional>
+
+class CppExampleProducer : public MessageProducer {
+public:
+ CppExampleProducer() {}
+ std::string get_message() const {
+ std::time_t result = std::time(nullptr);
+ std::ostringstream st;
+ st << std::asctime(std::localtime(&result))
+ << result << " seconds since the Epoch";
+ return st.str();
+ }
+};
+
+class CppExampleDisplayer : public MessageDisplayer {
+public:
+ CppExampleDisplayer() {}
+ void display_message(const std::string& msg) const {
+ std::cout << "Message: " << msg << std::endl;
+ }
+};
+
+std::vector<std::reference_wrapper<const MessageProducer>> producers;
+std::vector<std::reference_wrapper<const MessageDisplayer>> displayers;
+CppExampleProducer cpp_producer;
+CppExampleDisplayer cpp_displayer;
+
+
+// Maybe we should use a language which tracks lifetimes
+// better than this. If only such a language existed.
+void register_displayer(const MessageDisplayer& displayer) {
+ displayers.push_back(displayer);
+}
+
+void register_producer(const MessageProducer& producer) {
+ producers.push_back(producer);
+}
+
+void register_cpp_thingies() {
+ register_producer(cpp_producer);
+ register_displayer(cpp_displayer);
+}
+
+void run_demo() {
+ for (auto& producer: producers) {
+ auto msg = producer.get().get_message();
+ for (auto& displayer: displayers) {
+ displayer.get().display_message(msg);
+ std::cout << std::endl;
+ }
+ std::cout << std::endl;
+ }
+}
+