c – 重载运算符<<用于文本呈现
发布时间:2020-12-16 07:35:07 所属栏目:百科 来源:网络整理
导读:我想通过使用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}
我想通过使用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}; renderer->renderText(50,50,color,"Float %f followed by int %i",f,i); 这实际上工作正常,但我想知道是否可以创建一个允许我这样做的类: debug() << "My variables: " << i << "," << "f"; 我假设会有一个模板函数,它会根据输入类型构建传递给renderText()的字符串,但我不太清楚如何实现它. 解决方法
Rob的答案的另一种方法是在自定义记录器类中包含一个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,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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |