From 3c3d8d7c2671c4f1dbeea93eb41545895446d850 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Sun, 5 Nov 2023 11:54:41 +0100 Subject: [PATCH] feat: delegate constructor --- chapters/chapter_02/CMakeLists.txt | 3 ++- .../chapter_02/include/delegate_constructor.h | 10 +++++++++ .../chapter_02/src/delegate_constructor.cpp | 22 +++++++++++++++++++ src/main.cpp | 2 ++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 chapters/chapter_02/include/delegate_constructor.h create mode 100644 chapters/chapter_02/src/delegate_constructor.cpp diff --git a/chapters/chapter_02/CMakeLists.txt b/chapters/chapter_02/CMakeLists.txt index 5972957..2ffd009 100644 --- a/chapters/chapter_02/CMakeLists.txt +++ b/chapters/chapter_02/CMakeLists.txt @@ -8,7 +8,8 @@ add_library( src/range_based_for.cpp src/structured_binding.cpp src/type_inference.cpp - src/variadic_templates.cpp) + src/variadic_templates.cpp + src/delegate_constructor.cpp) target_compile_features(chapter_02 PUBLIC cxx_std_20) diff --git a/chapters/chapter_02/include/delegate_constructor.h b/chapters/chapter_02/include/delegate_constructor.h new file mode 100644 index 0000000..3ca9280 --- /dev/null +++ b/chapters/chapter_02/include/delegate_constructor.h @@ -0,0 +1,10 @@ +#pragma once + +#include "chapter_interface.h" + +class DelegateConstructor : public ChapterTest { + virtual void run() override; + virtual const char *name() const override { + return "Delegate constructor test"; + }; +}; diff --git a/chapters/chapter_02/src/delegate_constructor.cpp b/chapters/chapter_02/src/delegate_constructor.cpp new file mode 100644 index 0000000..4f5a0d9 --- /dev/null +++ b/chapters/chapter_02/src/delegate_constructor.cpp @@ -0,0 +1,22 @@ +#include "delegate_constructor.h" +#include +#include + +class Printer { +private: + std::string value; + +public: + Printer(const std::string &value) : value(value){}; + Printer(int value) : Printer(std::to_string(value)){}; + + void print() { std::cout << value << std::endl; } +}; + +void DelegateConstructor::run() { + std::cout << "print(\"hello\"): "; + Printer("hello").print(); + + std::cout << "print(23): "; + Printer(23).print(); +} diff --git a/src/main.cpp b/src/main.cpp index 07fcc69..e74c5a9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,6 +4,7 @@ #include #include "constexp.h" +#include "delegate_constructor.h" #include "if_constexpr.h" #include "ifswitch.h" #include "initlist.h" @@ -30,6 +31,7 @@ int main(int argc, char **argv) { chapter_2_tests.emplace_back(std::make_unique()); chapter_2_tests.emplace_back(std::make_unique()); chapter_2_tests.emplace_back(std::make_unique()); + chapter_2_tests.emplace_back(std::make_unique()); for (auto &test : chapter_2_tests) { std::cout << "\n" << test->name() << ":" << std::endl;