我创建了这个模板函数:
// 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;
}
但是我有这个错误:
error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream') and '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]
关于c++ - 通用容器的输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214136/