连接字符串并作为参数传递?

Concatenating a string and passing as a parameter?

我编写了自己的记录器,可以按如下方式使用:

LOG("This is the number five: " << 5 << ".");

我想编写一个错误检查方法,只需要一个 return 代码,检查它是否有错误,如果有则打印一条错误消息

因此,我想转:

if(result == -1)
{
    LOG("ERROR! We got a result of: " << result << ".");
    // Do some other stuff
}

进入:

checkForError(result, "ERROR! We got a result of: " << result << ".");

void checkForError(int result, SomeStringType message)
{
    if(result == -1)
    {
    LOG(message);
    // Do some other stuff
    } 
}

这可能吗?我试过将它作为 char*、std:string 和字符串流传递,但我似乎无法使其正常工作

有什么方法可以做到这一点,所以我只是在函数调用中连接错误消息吗?

是的,这是可能的。你可以这样做:

#define LOG(X)                                   \
        do {                                     \
            std::ostringstream log_stream;       \
            log_stream << X;                     \
            LOG::log_internal(log_stream.str()); \
        } while (0)

其中 LOG::log_internal 可能会在您的记录器 header 中声明为

struct LOG {
    static void log_internal(const std::string &);
};

这个的主要缺点是它不是有史以来最卫生的宏——如果参数 X 包含分号,那么您可以在宏的范围内执行其他语句,并且不会编译器错误。尽管在我看来这个宏远非神秘,幸运的是您实际上不必担心攻击者对您的宏执行 SQL-injection-esque 攻击。

我在我的项目中使用的记录器基本上是这样的,我从其他项目中学会了这样做。 (实际上我用的那个更发达一点,它也将 __FILE____LINE__ 传递给 LOG::log_internal 函数,并且有日志通道和日志级别,它们可能处于活动状态,也可能不处于活动状态等.等等...)