Skip to content

hw03 #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

hw03 #35

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions main.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
#include <iostream>
#include <ostream>
#include <type_traits>
#include <vector>
#include <variant>

// 请修复这个函数的定义:10 分
// A: 没有加模板声明
template<typename T>
std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
os << "{";
for (size_t i = 0; i < a.size(); i++) {
Expand All @@ -15,20 +19,38 @@ std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
}

// 请修复这个函数的定义:10 分
// 使用type_traits中的common_type
// 为了让返回值长度短点,能否修改下一行为
// template <class T1, class T2, class T3 = typename std::common_type<T1, T2>::type >
template <class T1, class T2>
std::vector<T0> operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
std::vector<typename std::common_type<T1, T2>::type> operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
// 请实现列表的逐元素加法!10 分
// 例如 {1, 2} + {3, 4} = {4, 6}
using elemtype = typename std::common_type<T1, T2>::type;
auto len = std::min(a.size(), b.size());
std::vector<elemtype> vec(len);
for (size_t i = 0; i != len; i++) {
vec[i] = a[i] + b[i];
}
return vec;
}

template <class T1, class T2>
std::variant<T1, T2> operator+(std::variant<T1, T2> const &a, std::variant<T1, T2> const &b) {
// 请实现自动匹配容器中具体类型的加法!10 分
return std::visit([](const auto &x, const auto &y) -> std::variant<T1, T2> {
return x + y;
}, a, b);
}

template <class T1, class T2>
std::ostream &operator<<(std::ostream &os, std::variant<T1, T2> const &a) {
// 踩坑:如果只有一个变长模板参数,则会默认实例化出来一个变长参数为空的实例出来
// 所以需要是 1 + * 的方式定义模板参数,不能只有一个 *
template <typename Arg, typename ... More>
std::ostream &operator<<(std::ostream &os, std::variant<Arg, More...> const &a) {
// 请实现自动匹配容器中具体类型的打印!10 分
return std::visit([&](const auto &x) -> std::ostream& {
return os << x;
}, a);
}

int main() {
Expand All @@ -46,7 +68,10 @@ int main() {

std::variant<std::vector<int>, std::vector<double>> d = c;
std::variant<std::vector<int>, std::vector<double>> e = a;
d = d + c + e;

// 这里vector不能隐式转换为variant, 可能是因为T1, T2模板参数推断不出来?
// 不知道如何解决,只能强制转换了。
d = d + static_cast<std::variant<std::vector<int>, std::vector<double>>>(c) + e;

// 应该输出 {9.28, 17.436, 7.236}
std::cout << d << std::endl;
Expand Down