比使用 s.str().c_str() 更好的表达?

Better expression than using s.str().c_str()?

本文关键字:str 更好      更新时间:2023-10-16
if ( hFileConnection == INVALID_HANDLE_VALUE ) {
std::stringstream s;
s << __func__ << " had GetLastError = " << GetLastError() << endl;
OutputDebugStringA( s.str().c_str() );
OutputDebugStringA( "n" );
}

我喜欢 <<运算符的可读性,但我想知道是否有更好的方法将其传输到调试,而不是 s.str((.c_str(( ?

我的视觉工作室"单元测试"在调试窗口中显示"Init had GetLastError = 2",因此代码确实有效。

通过编写一些代码来创建自己的界面。

void OutputDebug(const char* s)
{
OutputDebugStringA(s);
}
void OutputDebug(const std::string& s)
{
OutputDebug(s.c_str());
}
void OutputDebug(const std::stringstream& s)
{
OutputDebug(s.str());
}

if ( hFileConnection == INVALID_HANDLE_VALUE ) {
std::stringstream s;
s << __func__ << " had GetLastError = " << GetLastError() << endl;
OutputDebug(s);
OutputDebug("n");
}

如果你想花哨,你可以添加一个小类型并重载operator<<.

即使是像这样简单和不完整的东西也可能被证明是有用的,有时是你需要的所有幻想:

// Empty types are surprisingly useful.
// This one is only a "hook" that we can attach 'operator<<' to
// in order to use stream insertion syntax.
struct DebugOutput {};  
template<typename T>
DebugOutput& operator<<(DebugOutput& lhs, const T& rhs)
{
std::stringstream ss;
ss << rhs;
OutputDebugStringA(ss.str().c_str());
return lhs;
}
int main()
{
DebugOutput debug;
debug << "hello" << 23 << "n";
}