Dori
Dori

Reputation: 1055

Recursive vector template

I've written the following piece of code:

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;
}

This works fine for regular vector<int> instances, but what I want to do is this:

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

Instead, I get compilation errors (the following text, with a long list of candidates): test.cpp|212|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::vector<std::vector<int> >')|

I'd have thought the templated function could be used twice, recursively. Am I wrong? If not, what gives? If so, is there some way to make this generic without duplicating code?

Upvotes: 0

Views: 131

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

 #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";
 }

the above compiles and runs. Fix your typos, or be careful what namespace you are working with. Overloading operators in anything but the current namespace or in an ADL related one tends to fail.

Upvotes: 1

Related Questions