From b88c4a8cedf79c19e1c9379c506c7488ed60ade3 Mon Sep 17 00:00:00 2001 From: QifanWang Date: Thu, 24 Nov 2022 19:49:51 +0800 Subject: [PATCH] finish hw03 --- CMakeLists.txt | 2 ++ main.cpp | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 29b152c..b68624d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,3 +7,5 @@ if (NOT CMAKE_BUILD_TYPE) endif() add_executable(main main.cpp) + +target_include_directories(main PRIVATE .) \ No newline at end of file diff --git a/main.cpp b/main.cpp index d76cce7..eec1430 100644 --- a/main.cpp +++ b/main.cpp @@ -1,8 +1,10 @@ #include #include #include +#include // 请修复这个函数的定义:10 分 +template std::ostream &operator<<(std::ostream &os, std::vector const &a) { os << "{"; for (size_t i = 0; i < a.size(); i++) { @@ -16,19 +18,45 @@ std::ostream &operator<<(std::ostream &os, std::vector const &a) { // 请修复这个函数的定义:10 分 template -std::vector operator+(std::vector const &a, std::vector const &b) { +std::vector +operator+(std::vector const &a, std::vector const &b) { // 请实现列表的逐元素加法!10 分 // 例如 {1, 2} + {3, 4} = {4, 6} + // 当列表不等长时,取较短的 + size_t len = std::min(a.size(), b.size()); + std::vector ret; + for (size_t i = 0; i < len; ++i) + ret.push_back(a[i] + b[i]); + return ret; } -template -std::variant operator+(std::variant const &a, std::variant const &b) { +template +std::variant operator+(std::variant const &a, U &&b) { // 请实现自动匹配容器中具体类型的加法!10 分 + using decay_U = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v) { + return std::visit([&b](auto &&A) -> std::variant { + return A + b; + }, a); + } else if constexpr (std::is_same_v, decay_U>) { + return std::visit([](auto &&A, auto &&B) -> std::variant { + return A + B; + }, a, b); + } else { + std::cout << cpp_type_name>() << std::endl; + std::cout << cpp_type_name() << std::endl; + throw std::bad_variant_access{}; + } + } template std::ostream &operator<<(std::ostream &os, std::variant const &a) { // 请实现自动匹配容器中具体类型的打印!10 分 + std::visit([&os](auto &&val) { + os << val; + }, a); + return os; } int main() {