C++ 过载操作员<&书信电报;用于文本呈现
我想创建一个类,通过使用3D渲染器提供std::cout或类似QDebug的功能来帮助我进行调试 我现在使用的渲染器方法如下C++ 过载操作员<&书信电报;用于文本呈现,c++,templates,operator-overloading,C++,Templates,Operator Overloading,我想创建一个类,通过使用3D渲染器提供std::cout或类似QDebug的功能来帮助我进行调试 我现在使用的渲染器方法如下 IRenderer::renderText(int posX, int posY, const float* color, const char* text, ...); // E.g. int i; float f; float color[] = {1, 1, 1, 1}; renderer->renderText(50, 50, color, "Float
IRenderer::renderText(int posX, int posY, const float* color, const char* text, ...);
// E.g.
int i;
float f;
float color[] = {1, 1, 1, 1};
renderer->renderText(50, 50, color, "Float %f followed by int %i", f, i);
这实际上很好,但我想知道是否有可能创建一个类,允许我这样做:
debug() << "My variables: " << i << ", " << "f";
debug()我喜欢从std::ostream派生日志类,因此我得到了所有流的优点。诀窍是将所有特定于应用程序的代码放在关联的streambuf类中。考虑这个工作例子。要修改它以满足您的需要,只需重写CLogBuf::sync()
,如下所示:
int sync() {
renderer->renderText(50, 50, color, "%s", str());
str("");
return false;
}
例如:
#include <iostream>
#include <sstream>
class CLogger : public std::ostream {
private:
class CLogBuf : public std::stringbuf {
private:
// or whatever you need for your application
std::string m_marker;
public:
CLogBuf(const std::string& marker) : m_marker(marker) { }
~CLogBuf() { pubsync(); }
int sync() { std::cout << m_marker << ": " << str(); str(""); return !std::cout; }
};
public:
// Other constructors could specify filename, etc
// just remember to pass whatever you need to CLogBuf
CLogger(const std::string& marker) : std::ostream(new CLogBuf(marker)) {}
~CLogger() { delete rdbuf(); }
};
int main()
{
CLogger hi("hello");
CLogger bye("goodbye");
hi << "hello, world" << std::endl;
hi << "Oops, forgot to flush.\n";
bye << "goodbye, cruel world\n" << std::flush;
bye << "Cough, cough.\n";
}
#包括
#包括
类阻塞器:public std::ostream{
私人:
类CLogBuf:public std::stringbuf{
私人:
//或者你的申请需要的任何东西
std::字符串m_标记;
公众:
CLogBuf(const std::string&marker):m_marker(marker){}
~CLogBuf(){pubsync();}
int sync(){std::coutRob回答的另一种方法是在自定义记录器类中包含一个ostringstream
,并使用析构函数进行日志记录:
#include <iostream>
#include <sstream>
class MyLogger
{
protected:
std::ostringstream ss;
public:
~MyLogger()
{
std::cout << "Hey ma, I'm a custom logger! " << ss.str();
//renderer->renderText(50, 50, color, ss.str());
}
std::ostringstream& Get()
{
return ss;
}
};
int main()
{
int foo = 12;
bool bar = false;
std::string baz = "hello world";
MyLogger().Get() << foo << bar << baz << std::endl;
// less verbose to use a macro:
#define MY_LOG() MyLogger().Get()
MY_LOG() << baz << bar << foo << std::endl;
return 0;
}
#包括
#包括
类MyLogger
{
受保护的:
std::ostringstream ss;
公众:
~MyLogger()
{
std::难道你甚至不需要创建临时记录器:阻塞器(“hello”)@CongXu-是的,你需要命名对象。临时对象不能绑定到非常量引用,如操作符>(ostream&,const char*)
。看到没有使用流的方法吗?因为我正在处理的代码使用禁用iostreams的stlport。我现在有一个使用va_list的工作解决方案,仍然想知道如何使用宏而不是使用宏来实现它。我建议您定义模板MyLogger&操作符