比使用 s.str().c_str() 更好的表达?
Better expression than using s.str().c_str()?
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";
}
相关文章:
- C++:将控制台输出存储在宏中更好吗
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 什么是更好的做法?通过指针或标识符传递类成员?
- 寻求更好地理解标准::访问
- 线程消息传递或更好:在"大师班"中访问其他班级的成员
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 如何更好地检查两个 char 变量是否在一组值中?
- 有没有更好的方法对C++中的三个整数进行排序?
- 什么模板用法在阶乘中更好
- 平面缓冲区可以利用向量中的 0 吗?还是其他小波比哈尔变换更好?
- 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 比使用 s.str().c_str() 更好的表达?
- 测量时间以在 c++ 中生成更好的随机数