Skip to content

实现了变长模板 #47

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 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@

## 关于内卷

如果你把 variant 的 operator<< 改成了基于变长模板参数的,或是实现了其他运算符:
如果你把 variant 的 `operator<<` 改成了基于变长模板参数的,或是实现了其他运算符:
只要是在 **满足作业要求的基础** 上,这是件好事!
老师会酌情加分,视为“独特的创新点”,但最多不超过 20 分。
28 changes: 22 additions & 6 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <variant>

// 请修复这个函数的定义:10 分
template <class T>
std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {
os << "{";
for (size_t i = 0; i < a.size(); i++) {
Expand All @@ -16,19 +17,34 @@ std::ostream &operator<<(std::ostream &os, std::vector<T> const &a) {

// 请修复这个函数的定义:10 分
template <class T1, class T2>
std::vector<T0> operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
auto operator+(std::vector<T1> const &a, std::vector<T2> const &b) {
// 请实现列表的逐元素加法!10 分
// 例如 {1, 2} + {3, 4} = {4, 6}
std::vector<decltype(T1() + T2())> c(std::min(a.size(), b.size()));
for (int i = 0; i < c.size(); i++) c[i] = a[i] + b[i];
return c;
}

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

template <class T1, class T2>
std::ostream &operator<<(std::ostream &os, std::variant<T1, T2> const &a) {
template <class T, class... V>
auto operator+(T const &a, std::variant<V...> const &b) {
return std::visit([&](auto const &x) {
return a + x; }, b);
}

template <class R, class... T>
std::ostream &operator<<(std::ostream &os, std::variant<R, T...> const &a) {
// 请实现自动匹配容器中具体类型的打印!10 分
return std::visit([&](auto const &x) -> std::ostream & {
os << x;
return os;
}, a);
}

int main() {
Expand All @@ -44,7 +60,7 @@ int main() {
// 应该输出 {4.14, 6.718, 2.618}
std::cout << c << std::endl;

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

Expand Down