gpt4 book ai didi

c++ - 通用容器的输出流

转载 作者:行者123 更新时间:2023-12-01 14:43:59 24 4
gpt4 key购买 nike

我创建了这个模板功能:

// 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/

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