gpt4 book ai didi

c++ - 我可以重载插入运算符以采用模板化 STL 容器吗?

转载 作者:可可西里 更新时间:2023-11-01 16:22:04 25 4
gpt4 key购买 nike

<分区>

我有这个关于 STL 容器的示例,所以我正在阅读它们,重复使用 range-for 对我来说太乏味了循环打印容器的内容。所以我想到重载插入运算符 <<因此我可以写:std::cout << container << std::endl; .

template<class T>
std::ostream& operator<<(std::ostream& out, const std::list<T>& v) {
for (const auto& e : v)
out << e << ", ";
return out;
}

int main() {

std::list<int> vi{ 10, 24, 81, 57, 2019 };

vi.pop_back();
std::cout << vi << std::endl; // 10, 24, 81, 57,

std::deque<std::string> names{ "Hello", "STL Containers" };
std::cout << names << std::endl; // error here. Bacause I've not overloaded << to take a std::deque<T>


}

正如您在上面看到的,我发现打印 list 很舒服某种类型的。问题是我只能打印一个列表,而不能打印其他类型的容器,比如 vectordeque ...

那么我怎样才能重载<<拿一个 T<U> 类型的容器还是我应该专门针对所有容器?在一个真实的例子中,我不应该那样做吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com