I am trying to print an STL container. I am trying to print container elements separated by a separator. However, I ran into several problems.
1.g ++ vs VC ++
ostream& operator<<(ostream& o, const vector<string>& v) {
copy(v.begin(), v.end(), std::ostream_iterator<string>(o,","));
}
int main()
{
vector<string> s_v;
s_v.push_back("one");
s_v.push_back("two");
cout << s_v;
}
g ++ (gcc version 4.4.0 on mingw32) can compile it, works fine. VC ++ (Visual Studio 9) cannot compile this code.
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion)
1> c:\program files (x86)\microsoft visual studio 9.0\vc\include\ostream(653): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
Why is this? Is this code illegal? or is it just VC ++ beign VC ++?
2. An unused template variable breaks compilation.
if now I add a template to a body like this (it is not used, it just sits there)
template <typename T>
ostream& operator<<(ostream& o, const vector<string>& v) {
copy(v.begin(), v.end(), std::ostream_iterator<string>(o,","));
}
int main()
{
vector<string> s_v;
s_v.push_back("one");
s_v.push_back("two");
cout << s_v;
}
gcc can no longer match the statement.
error: no match for 'operator<<' in 'std::cout << s_v'
and a lot more candidates...
Why? the template is not used. Should it make a difference?
EDITOR: This is decided. I had to return o;
3. Used pattern
template <typename T>
ostream& operator<<(ostream& o, const vector<T>& v) {
copy(v.begin(), v.end(), std::ostream_iterator<T>(o,","));
return o;
}
int main()
{
vector<string> s_v;
s_v.push_back("one");
s_v.push_back("two");
vector<int> i_v;
i_v.push_back(1);
i_v.push_back(2);
cout << s_v;
cout << i_v;
}
, . g++ , .
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
V++ , gcc . .
- ? .