fla*_*006 1 c++ templates operator-overloading operators stringstream
我创建了一个名为SkipToChar的类,它应该能够按如下方式使用:
std::ostringstream oss;
oss << "Hello," << SkipToChar(7) << "world!" << std::endl;
Run Code Online (Sandbox Code Playgroud)
哪个会打印"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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,它给我以下错误:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'basic_SkipToChar<char>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)
我用注释标记了错误所在的行.这里出了什么问题?
oss << "Hello,"
返回std::basic_ostream<char>
(它丢失了字符串部分).
所以你的方法不匹配(期望std::basic_ostringstream
但得到std::basic_ostream<char>
).