Concatenating a string and passing as a parameter?

时间:2015-09-01 21:52:47

标签: c++ string concatenation

I wrote my own logger that I can use as follows:

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

I'd like to write an error checking method that simply takes a return code, checks if it's an error, and if so prints an error message

Thus, I'd like to turn:

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

into:

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

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

is this possible? I've tried passing it as a char*, a std:string, and as a stringstream, but I can't seem to get it to work correctly

Is there any way to do this so I'm simply concatenating the error message in the call to the function?

1 个答案:

答案 0 :(得分:1)

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

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

其中LOG::log_internal可能会在您的记录器标头中声明,如

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

这样做的主要缺点是它不是最卫生的宏 - 如果参数X包含分号,那么你可以在宏的范围内执行其他语句,并且不会出现编译错误。在我看来,这个宏远非神秘,幸运的是你实际上不必担心攻击者对你的宏执行SQL注入式攻击。

我在我的项目中使用基本上看起来像这样的记录器,并且我学会了从其他项目中这样做。 (实际上我使用的是一个更开发的,它还将__FILE____LINE__传递给LOG::log_internal函数,以及可能存在或可能存在的日志通道和日志级别不活跃等等...)