使用预处理器C++定义常见错误消息

Defining common error messages with preprocessor C++

本文关键字:常见 错误 消息 定义 C++ 预处理 处理器      更新时间:2023-10-16

假设我有多个地方调用函数int foo(x, y)。根据返回代码,我决定是否打印错误消息。所以代码看起来类似于这样:

  void func1()
    {
        ...
        if(foo(x,y))
            std::cerr << "Error occurred with values" << x << "," << y << __LINE__;
        ...
    }
    void func2()
    {
        ...
        if(foo(x,y))
            std::cerr << "Error occurred with values" << x << "," << y << __LINE__;
        ...
    }

我遇到的问题是"Error occurred"在许多地方重复,到处都是一样的。我想知道使用 #define 定义常见错误消息并重用它们是否是一种好习惯。所以代码是这样的:

  #define errMsg(x,y) 
    std::string("Error occurred with values " + to_string(x) + "," + to_string(y) + to_string(__LINE__))
  void func1()
    {
        ...
        if(foo(x,y))
            std::cerr << errMsg;
        ...
    }
    void func2()
    {
        ...
        if(foo(x,y))
            std::cerr << errMsg;
        ...
    }

显而易见的事情就是将错误消息放在foo本身中。 如果你做不到,那就把它包装起来:

bool fooWithLogging(int x, iny y)
{
    auto result = foo(x,y);
    if (result)
    {
        std::cerr << "Error occurred with values" << x << "," << y << std::endl;
    }
}

在代码中调用包装器:

void func1()
{
    ...
    fooWithLogging(x,y);
    ...
}
void func2()
{
    ...
    fooWithLogging(x,y);
    ...
}

奖励:使日志记录动态化:

#ifdef DEBUG
bool g_isFooLoggingEnabled = true;
#else
bool g_isFooLoggingEnabled = false;
#endif
bool fooWithLogging(int x, iny y)
{
    auto result = foo(x,y);
    if (result && g_isFooLoggingEnabled)
    {
        std::cerr << "Error occurred with values" << x << "," << y << std::endl;
    }
}

现在,有了刚刚在评论中提到的文件和行要求:

bool _fooWithLogging(int x, iny y, const std::string& filename, int line)
{
    auto result = foo(x,y);
    if (result && g_isFooLoggingEnabled)
    {
        std::cerr << "Error occurred in file" << filename << " on line " << line << " with values" << x << "," << y << std::endl;
    }
}
#define FooWithLogging(x, y) _fooWithLogging(x, y, __FILE__, __LINE__)

然后在代码中:

void func1()
{
    ...
    FooWithLogging(x,y);
    ...
}