【问题标题】:Recursive vector template递归向量模板
【发布时间】: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&lt;int&gt; 实例,但我想要做的是:

vector<vector<int> > v={{1,2},{3,4}}
cout << v; // Should print {{1 2 } {3 4 } }

相反,我收到编译错误(以下文本,包含一长串候选者):test.cpp|212|error: no match for 'operator&lt;&lt;' (operand types are 'std::ostream {aka std::basic_ostream&lt;char&gt;}' and 'std::vector&lt;std::vector&lt;int&gt; &gt;')|

我原以为模板函数可以递归使用两次。我错了吗?如果没有,什么给出?如果是这样,有什么方法可以在不重复代码的情况下使其通用?

【问题讨论】:

标签: c++ templates vector operator-overloading


【解决方案1】:
 #include <iostream>
 #include <vector>

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

 int main(){
   std::vector<int> v1{1,2,3};
   std::cout<<v1<<"\n";
   std::vector<std::vector<int>> v2{{1},{2,3}};
   std::cout<<v2<<"\n";
 }

以上编译并运行。修正你的拼写错误,或者小心你正在使用的命名空间。在除当前命名空间或 ADL 相关命名空间之外的任何地方重载运算符往往会失败。

【讨论】:

    猜你喜欢
    • 2015-05-20
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多