hey*_*ude 2 c++ stringstream visual-studio-2008-sp1 visual-studio
我遇到了一个奇怪的问题stringstream.
#include "stdafx.h"
#include "iostream"
#include "sstream"
using namespace std;
struct Test
{
float f;
};
wstringstream& operator <<( wstringstream& sstream , const Test& test )
{
sstream << test.f;
return sstream;
}
int _tmain(int argc, _TCHAR* argv[])
{
Test a;
a.f = 1.2f;
wstringstream ss;
ss << L"text" << a << endl; // error C2679!
ss << a << L"text" << endl; // it works well..
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题出在这里:
ss << L"text" << a << endl; // error C2679!
ss << a << L"text" << endl; // it works well..
Run Code Online (Sandbox Code Playgroud)
这两个语句之间的唯一区别是参数顺序.为什么第一个语句失败而第二个语句有效?
不要限制你的operator<<工作wstringstream,写它以便它适用于任何广泛的流:
std::wostream& operator <<(std::wostream& sstream, Test const& test)
{
return sstream << test.f;
}
Run Code Online (Sandbox Code Playgroud)
或任何流(宽或窄):
template<typename CharT, typename TraitsT>
std::basic_ostream<CharT, TraitsT>&
operator <<(std::basic_ostream<CharT, TraitsT>& sstream, Test const& test)
{
return sstream << test.f;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
474 次 |
| 最近记录: |