【发布时间】:2017-04-15 18:10:24
【问题描述】:
我编写了以下代码:
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "{";
for (auto i=v.begin(); i!=v.end(); ++i) {
os << *i << " ";
}
os << "}";
return os;
}
这适用于常规 vector<int> 实例,但我想要做的是:
vector<vector<int> > v={{1,2},{3,4}}
cout << v; // Should print {{1 2 } {3 4 } }
相反,我收到编译错误(以下文本,包含一长串候选者):test.cpp|212|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::vector<std::vector<int> >')|
我原以为模板函数可以递归使用两次。我错了吗?如果没有,什么给出?如果是这样,有什么方法可以在不重复代码的情况下使其通用?
【问题讨论】:
-
如果您不理解错误信息,不建议对其进行总结。
标签: c++ templates vector operator-overloading