c++ - 通用容器的输出流
问题描述
我创建了这个模板函数:
// Output stream for container of type C
template<class C>
ostream& operator<<(ostream& os, const C& c) {
os << "[";
for (auto& i : c) {
os << i;
if (&i != &c.back()) os << ", ";
}
os << "]" << endl;
return os;
}
但我有这个错误:
错误:重载运算符“<<”的使用不明确(操作数类型为“std::ostream”(又名“basic_ostream”)和“const char [2]”)
错误出现在函数主体的第一行。
解决方案
本声明
template<class C>
ostream& operator<<(ostream& os, const C& c)
是任何类型的匹配项。特别是,当您在该运算符内部调用时
os << "[";
os << i;
os << "]" << endl;
对于所有这些调用,除了字符串和endl
.
不要为您不拥有的类型提供运算符。相反,你可以写一个
void print(const my_container&);
或使用标签来解决歧义。例如,您可以使用
template <typename T>
struct pretty_printed_container {
const T& container;
};
template <typename T>
pretty_printed_container<T> pretty_print(const T& t) { return {t};}
相应地修改您的输出运算符
template<class T>
std::ostream& operator<<(std::ostream& os, const pretty_printed_container<T>& c) {
os << "[";
for (const auto& i : c.container) {
os << i;
if (&i != &c.container.back()) os << ", ";
}
os << "]" << std::endl;
return os;
}
然后像这样使用它
int main() {
std::vector<int> x{1,2,3,4,5};
std::cout << pretty_print(x);
}
输出:
[1, 2, 3, 4, 5]
推荐阅读
- javascript - 中间件被调用以进行错误处理但不处理响应
- amazon-web-services - DynamoDB 拒绝除管理员和 Lambda 函数之外的所有人访问
- php - Strpos 返回误报,搜索特定单词的更好的 php 函数是什么?
- git - 尝试删除未推送到主分支的单个提交
- laravel - SQLSTATE[23000] 通过添加一个虚拟测试
- mysql - 如何使用 BETWEEN DATE 条件在交叉/左连接 MYSQL 中显示空值或零值
- bootstrap-4 - Bootstrap datetimepicker小部件如何允许无效的mysql日期,如'0000-00-00'?
- java - 为什么 BinaryGap 对于 trailing_zeroes 不正确(n = 6 和 n = 328)
- enums - 无法移出“Rc”
- c# - 将给定的单词随机排列到矩阵中