【发布时间】:2015-03-03 22:19:42
【问题描述】:
我创建了一个名为 SkipToChar 的类,它应该可以按如下方式使用:
std::ostringstream oss;
oss << "Hello," << SkipToChar(7) << "world!" << std::endl;
将打印“Hello, world!” (注意空格。)基本上它应该使用空格跳到指定索引处的字符。但显然编译器无法识别我为它创建的operator<<。有趣的是,显式调用operator<<,即使没有提供任何模板参数(如operator<<(oss, SkipToChar(7)); 工作正常;如果我实际使用它就行不通
这是我的代码:
#include <iostream>
#include <sstream>
template <typename _Elem>
struct basic_SkipToChar
{
typename std::basic_string<_Elem>::size_type pos;
basic_SkipToChar(typename std::basic_string<_Elem>::size_type position)
{
pos = position;
}
};
template <typename _Elem>
inline std::basic_ostringstream<_Elem> &operator<<(std::basic_ostringstream<_Elem> &oss, const basic_SkipToChar<_Elem> &skip)
{
typename std::basic_string<_Elem>::size_type length = oss.str().length();
for (typename std::basic_string<_Elem>::size_type i = length; i < skip.pos; i++) {
oss << (_Elem)' ';
}
return oss;
}
typedef basic_SkipToChar<char> SkipToChar;
typedef basic_SkipToChar<wchar_t> WSkipToChar;
int main(int argc, char *argv[])
{
std::ostringstream oss;
/*ERROR*/ oss << "Hello," << SkipToChar(8) << "world!" << std::endl;
std::cout << oss.str();
return 0;
}
当我尝试编译它时,它给了我以下错误:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'basic_SkipToChar<char>' (or there is no acceptable conversion)
我用注释标记了错误所在的行。这里出了什么问题?
【问题讨论】:
-
最好只重载
operator<<(std::ostream&, whatever),因为std::ostream&是这些运算符通常返回的,因此在连接调用时会得到什么,如out << a << b << c;
标签: c++ templates operator-overloading operators stringstream