Brian Silverman | 4e662aa | 2022-05-11 23:10:19 -0700 | [diff] [blame^] | 1 | // Copyright 2021 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
| 6 | // option. This file may not be copied, modified, or distributed |
| 7 | // except according to those terms. |
| 8 | |
| 9 | // This example shows Rust subclasses of C++ classes. |
| 10 | // See messages.h and main.rs for most of the interesting code. |
| 11 | |
| 12 | #include "messages.h" |
| 13 | #include <ctime> |
| 14 | #include <iostream> |
| 15 | #include <sstream> |
| 16 | #include <vector> |
| 17 | #include <functional> |
| 18 | |
| 19 | class CppExampleProducer : public MessageProducer { |
| 20 | public: |
| 21 | CppExampleProducer() {} |
| 22 | std::string get_message() const { |
| 23 | std::time_t result = std::time(nullptr); |
| 24 | std::ostringstream st; |
| 25 | st << std::asctime(std::localtime(&result)) |
| 26 | << result << " seconds since the Epoch"; |
| 27 | return st.str(); |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | class CppExampleDisplayer : public MessageDisplayer { |
| 32 | public: |
| 33 | CppExampleDisplayer() {} |
| 34 | void display_message(const std::string& msg) const { |
| 35 | std::cout << "Message: " << msg << std::endl; |
| 36 | } |
| 37 | }; |
| 38 | |
| 39 | std::vector<std::reference_wrapper<const MessageProducer>> producers; |
| 40 | std::vector<std::reference_wrapper<const MessageDisplayer>> displayers; |
| 41 | CppExampleProducer cpp_producer; |
| 42 | CppExampleDisplayer cpp_displayer; |
| 43 | |
| 44 | |
| 45 | // Maybe we should use a language which tracks lifetimes |
| 46 | // better than this. If only such a language existed. |
| 47 | void register_displayer(const MessageDisplayer& displayer) { |
| 48 | displayers.push_back(displayer); |
| 49 | } |
| 50 | |
| 51 | void register_producer(const MessageProducer& producer) { |
| 52 | producers.push_back(producer); |
| 53 | } |
| 54 | |
| 55 | void register_cpp_thingies() { |
| 56 | register_producer(cpp_producer); |
| 57 | register_displayer(cpp_displayer); |
| 58 | } |
| 59 | |
| 60 | void run_demo() { |
| 61 | for (auto& producer: producers) { |
| 62 | auto msg = producer.get().get_message(); |
| 63 | for (auto& displayer: displayers) { |
| 64 | displayer.get().display_message(msg); |
| 65 | std::cout << std::endl; |
| 66 | } |
| 67 | std::cout << std::endl; |
| 68 | } |
| 69 | } |
| 70 | |