在头文件中设置 std::boolalpha 标志?

问题描述 投票:0回答:1

是否可以在头文件中设置

std::boolalpha
?我的用例是在需要时轻松地跨文件进行打印调试。我可以将它们放在同一个标题中,并将重载放在
std::ostream& operator<<
上,而不是在
main()
中输入。

c++ iostream
1个回答
1
投票

如何继续注销生产代码并在其他地方进行格式化和选择日志机制的示例。

#include <iostream>
#include <string>

// Header file my_reporting_itf.h
struct my_reporting_itf
{
    // logging my never change the state of the object
    // and must not throw (logging infrastructure error should be handled and hidden)
    virtual void report_input_out_of_range(const std::string& value_name, int value) const noexcept = 0;
};

// Header file and C++ file std_cout_reporting_t.h and std_cout_reporting_t.cpp
// include my_reporting_itf.h
// in the cpp file you can use your 
struct std_cout_reporting_t final :
    public my_reporting_itf
{
    // forward to logging infrastructure of your choice
    void report_input_out_of_range(const std::string& value_name, int value) const noexcept override
    {
        // here is where you manage your logging formatting, and things like std::boolalpha
        // the setting could be a flag in std_cout_reporting_t's constructor
        std::cout << "Value : `" << value_name << "` is out of range, value = " << value << "\n";
    }
};

// Header file and C++ file null_reporting_t.h and null_reporting_t.cpp
// include my_reporting_itf.h
struct null_reporting_t :
    public my_reporting_itf
{
    // for unit testing do absolutely nothing
    void report_input_out_of_range(const std::string& value_name, int value) const noexcept override
    {
    }
};

// myclass.cpp and myclass.h
// A class with logging like this is unit testable
// in the header file for my_class_t you only have to include header file with my_reporting
// include my_reporting_itf.h (not dependend on any logging infrastructure
class my_class_t
{
public:
    explicit my_class_t(const my_reporting_itf& report) :
        m_report{ report }
    {
    };

    void set_value(int value)
    {
        if (value < 0)
        {
            m_report.report_input_out_of_range("value", value);
        }
    }

private:
    const my_reporting_itf& m_report;
};

// main.cpp
// here you include my_class_t.h, and std_cout_reporting_t.h
int main()
{
    std_cout_reporting_t report;
    // null_reporting_t report; for unit testing inject this (you can also inject a google_mock to test
    // if report functions are actually called when needed)
    
    my_class_t foo{ report };

    // out of range will result in a report
    foo.set_value(-1);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.