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

Defining common error messages with preprocessor C++

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

  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;
    }
}

现在有了您刚刚在评论中提到的 FILE 和 LINE 要求:

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);
    ...
}