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

时间:2019-01-17 01:00:00

标签: c++ error-handling c-preprocessor

比方说,我在多个地方调用函数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;
        ...
    }

1 个答案:

答案 0 :(得分:1)

显而易见的事情就是将错误消息放入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);
    ...
}