【问题标题】:printing/log c++ stings indented w.r.t. depth of function call打印/记录 c++ stings 缩进 w.r.t.函数调用深度
【发布时间】:2021-12-08 01:52:43
【问题描述】:

我想在函数中打印一些字符串,但缩进取决于函数调用的深度。到目前为止,我的解决方案包括来自 this thread 的类,如下所示:

class DepthCounter
{
    static int depth;

public:
    DepthCounter(const std::string& name)
    {
        std::cout << std::string(depth*2, ' ') << name << "  // depth " << depth << '\n';
        ++depth;
    }

    ~DepthCounter()
    {
        --depth;
    }
};

int DepthCounter::depth = 0;

void func1(){
    DepthCounter dc("name1");
}

void func2(){
    DepthCounter dc("name2");
    func1();
}

所以第一个构造中的打印将具有 1 深度和第二个 2 深度(缩进)。 但我想多次打印。那是

void func2(){
    DepthCounter dc("name0");
    DepthCounter dc1("name1");
    DepthCounter dc2("name2");
    DepthCounter dc3("name3");
    func1();
}

但我不觉得它很好,更不用说这种结构增加了深度,尽管它仍然具有相同的功能。有没有更好的方法来实现这样的功能?

理想情况下,我想要这样的东西:

void func1(){
    funcX("name5");
}

void func2(){
    funcX("name0");
    funcX("name1");
    funcX("name2");
    funcX("name3");
    func1();
}

有人知道另一种方法吗?

【问题讨论】:

  • 如果你想要多个深度计数器,你可以用int参数把它做成一个模板。这将允许同时管理多个此类计数器,而无需过多地改变您的概念。
  • 也许,您正在寻找一种堆栈跟踪(也称为调用堆栈),就像您可能已经在 gdb 中看到的那样。我大概记得曾经有过这样一个问题。 gdb 的堆栈跟踪部分由一个库提供,该库也可以在您的应用程序中使用。尽管如此,它可能总是依赖于平台的解决方案,因为这些细节通常是实现细节的主题,而不是 C++ 标准。
  • Alipapa:这个答案有帮助吗?请询问是否不清楚。

标签: c++ logging


【解决方案1】:

您可以将函数名称存储在 DepthCounter 中,并提供 operator&lt;&lt; 重载以在函数内部使用:

class DepthCounter {
    static int depth;
    std::string m_name;
public:
    DepthCounter(const std::string& name) : m_name(name) {
        std::cout << std::string(depth*2, ' ') << "->" << m_name << '\n';
        ++depth;
    }
    ~DepthCounter() {
        --depth;
        std::cout << std::string(depth*2, ' ') << "<-" << m_name << '\n';
    }

    template<class T>
    friend DepthCounter& operator<<(DepthCounter& dc, const T& val) {
        std::cout << std::string(depth*2, ' ') << dc.m_name << ": " << val << '\n';
        return dc;
    }
};

int DepthCounter::depth = 0;

然后像这样使用它:

void func1(){
    DepthCounter dc(__func__);
    dc << "here's something";
}

void func2(){
    DepthCounter dc(__func__);
    dc << "name1";
    dc << "name2";
    func1();
    dc << "some more after calling func1";
}

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多