問題:的std :: ostream的私人繼承和使用operator <<
#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> ::操作者< <':5重載有類似的轉換
我在做什麼錯誤或是這是另一個MS Visual Studio的錯誤?
解決方法: 添加以下成員方法似乎可行,但我想深入瞭解根本原因。
MyClass& operator<<(const char* str) {
std::ostream& os = *this;
os << str;
return *this;
}
背景:的MySQL ++不使用Visual Studio 2010(見mailing list),因爲VS2010不支持的公有繼承(除其他事項外)的std :: ostream的編譯。作爲解決辦法,我試圖進行私有繼承,因爲它比組合更少。 MyClass &運營商< <(const char * str){ std :: ostream & os = * this; os < < str; return * this; }
完整的錯誤消息
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])'
這是完整的錯誤信息嗎?通常模板錯誤較長。如果還有更多請發佈。 – Borgleader
這不是一個模板錯誤消息 - 但它確實列出了5個重載方法。我已經編輯完整性。 – Zero