问题:
#include <iostream>
#include <sstream>
class MyClass : private std::ostream
{
public :
MyClass() : std::ostream(&mBuffer) { }
using std::operator<<;
private:
std::stringbuf mBuffer;
};
// In main function, for example
MyClass c;
c << 'A' << "Hello, World!"; // Works
c << "Hello, World!" << 'A'; // ERROR
错误 (MS Visual Studio 2010) 是错误 C2666: 'std::basic_ostream<_Elem,_Traits>::operator <<' : 5 重载具有类似的转换
我做错了什么还是这是另一个 MS Visual Studio 错误?
解决方法: 添加以下成员方法似乎可行,但我想深入了解根本原因。
MyClass& operator<<(const char* str) {
std::ostream& os = *this;
os << str;
return *this;
}
背景: MySql++ 不能与 Visual Studio 2010 一起编译(参见邮件列表),因为 VS2010 不支持(除其他外)std::ostream 的公共继承。作为一种解决方法,我正在尝试私有继承,因为这比组合更少黑客攻击。MyClass& 运算符<<(const char* str) { std::ostream& os = *this; 操作系统 << str; 返回*这个;}
完整的错误信息
1>d:\repo\test\test\main.cpp(30): error C2666: 'std::basic_ostream<_Elem,_Traits>::operator <<' : 5 overloads have similar conversions
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(206): could be 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::_Bool)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(467): or 'std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(const void *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(851): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const _Elem *)' [found using argument-dependent lookup]
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(764): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): or 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> while trying to match the argument list '(MyClass, const char [14])'