2017-04-15 20 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> >')|

テンプレート化された関数を再帰的に2回使用できると思いました。私が間違っている?そうでない場合、何が得られますか?もしそうなら、コードを複製せずにこのジェネリックを作る方法がありますか?

+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関連のもの以外のもので演算子をオーバーロードすると失敗する傾向があります。

関連する問題