1. g++与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++(在mingw32上的gcc版本4.4.0)可以编译它并且运作良好。VC ++(Visual Studio 9)无法编译此代码。
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> [
为什么会这样?这段代码是不合法的吗?还是说这只是VC++本身的问题?
2. 未使用的模板变量会导致编译错误。
如果现在我向ostream添加一个模板,像这样(它没有被使用,只是存在)
template <typename T> // <----- Here
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无法匹配运算符。
error: no match for 'operator<<' in 'std::cout << s_v'
and a lot more candidates...
为什么模板没有使用?这会有影响吗?
编辑:问题已解决。我必须返回o;
3. 使用的模板
template <typename T>
ostream& operator<<(ostream& o, const vector<T>& v) {
copy(v.begin(), v.end(), std::ostream_iterator<T>(o,","));
return o; // Edited
}
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
VC++ 只是坐着看 gcc 做所有这些事情,不编译任何内容。
能否有人为我澄清这些事情?谢谢。
std::
中定义运算符。否则,代码是非法的。 - James Kanzestd::
,缺少返回值),它就可以在我的系统上运行(VC++ 11)。 - James Kanze