【发布时间】:2013-01-28 06:06:20
【问题描述】:
我正在尝试在 ostringstream 实例上创建一个瘦包装器,它将所有插入操作委托给封闭的 ostringstream 实例。这个想法是保留类型 在进行级联插入操作时。通常,级联插入操作的结果类型是 ostream&,并且任何原始类型都会丢失。我想维护表达式的类型,因为我希望能够将它传递给一个方法以进行进一步处理,并且希望能够访问底层的 ostringstream 以获取插入的字符串数据。
我希望能够执行以下操作,并将表达式的结果设为 LgStream:
LgStream() << 26 << " a plain string " << std::string("a std string") << someObjWithItsOwnInsertionOperator;
所以我为基本类型定义了操作符
class LgStream
{
public:
ostringstream m_oss;
string str() {return m_oss.str();}
LgStream &operator<<(int x) {m_oss << x; return *this;}
LgStream &operator<<(long x) {m_oss << x; return *this;}
LgStream &operator<<(char x) {m_oss << x; return *this;}
LgStream &operator<<(bool x) {m_oss << (x ? 'T':'F'); return *this;}
LgStream &operator<<(double x) {m_oss << x; return *this;}
template <typename T>
LgStream &operator<<(const T &x) {m_oss << x; return *this;}
template <typename T>
LgStream &operator<<(const T x) {m_oss << x; return *this;}
};
我没有正确,并且收到“模棱两可的过载”错误。例如:
LgStream() << "This is a plain string";
error: ambiguous overload for 'operator<<' in 'LgStream() << "This is a plain string"'
note: candidates are:
note: LgStream& LgStream::operator<<(int) <near match>
note: no known conversion for argument 1 from 'const char [23]' to 'int'
note: LgStream& LgStream::operator<<(long int) <near match>
note: no known conversion for argument 1 from 'const char [23]' to 'long int'
note: LgStream& LgStream::operator<<(char) <near match>
note: no known conversion for argument 1 from 'const char [23]' to 'char'
note: LgStream& LgStream::operator<<(bool)
note: LgStream& LgStream::operator<<(std::string)
note: LgStream& LgStream::operator<<(const T&) [with T = char [23], LgStream = LgStream]
note: LgStream& LgStream::operator<<(T) [with T = const char*, LgStream = LgStream]
任何一种语法的帮助,或者如果我采取了错误的方法。
【问题讨论】:
标签: c++ operator-overloading insertion ambiguous