2017-04-15 113 views
0

我已经写了下面的一段代码:递归矢量模板

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> >')|

我以为模板函数可以使用两次,递归。我错了吗?如果不是,是什么给了?如果是这样,有没有办法使这个通用的没有重复的代码?

+0

如果您不明白错误消息,则不建议对其进行汇总。 – Yakk

+1

提供[MCVE]。 – Yakk

回答

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相关命名空间之外的任何内容中重载运算符往往会失败。