c – 重载运算符<

我想通过使用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 %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, 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;
}
点赞