2013-10-03 10 views
8

ので、STDで遊んでいる間::配列は、私は、配列のすべての要素をプリントアウトするための簡単な方法を望んでいたし、次を試してみました:STDの印刷::配列

using namespace std; 

template <class T, int N> 
ostream& operator<<(ostream& o, const array<T, N>& arr) 
{ 
    copy(arr.cbegin(), arr.cend(), ostream_iterator<T>(o, " ")); 
    return o; 
} 

int main() 
{ 
    array<int, 3> arr {1, 2, 3}; 
    cout << arr; 
} 

しかし、いつでも私はこれを実行しようとすると、次のエラーが表示されます。

test.cpp: In function 'int main()': 
test.cpp:21:10: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' 
c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream:581:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = std::array<int, 3u>]' 

このエラーが何を意味するのか、どのように修正するかについてのアイデアはありますか?

私は、テンプレート< ...> print_array(constの配列&)のような関数でエラーが変更オペレータ< <を交換する場合:

test.cpp: In function 'int main()': 
test.cpp:20:17: error: no matching function for call to 'print_array(std::array<int, 3u>&)' 
test.cpp:20:17: note: candidate is: 
test.cpp:12:6: note: template<class T, int N> void print_array(const std::array<T, N>&) 
+1

どのコンパイラですか?あなたのコードはVisual C++ 2012でコンパイルされて実行されるため、 – Alex

+3

std :: arrayは ''ではなく ''です。あなたのコンパイラが一致するものを見つけられないかもしれません。 4.7または4.8にアップグレードできますか? 4.6は完全にC++ 11に準拠していませんでした。 –

+1

[IDEONE](http://ideone.com/9JzUr9)で動作しますが、 'int'を' size_t'に変更しなければなりませんでした。 – jxh

答えて

9

使用std::size_t種類を推定するコンパイラを助けるために:

template <class T, std::size_t N> 
ostream& operator<<(ostream& o, const array<T, N>& arr) 
{ 
    copy(arr.cbegin(), arr.cend(), ostream_iterator<T>(o, " ")); 
    return o; 
}