1

我正在努力实现这一目标:

#include <iostream>
#include <sstream>

void log(
        const char* argFile,
                int argLineNb,
                const char* argFunction,
                std::stringstream& argString) {
    std::cout << argFile << ":" << argLineNb << " " << argFunction
        << " " << argString.str()<< std::endl;
}


/**
 * \brief       Macro declarations
 */

#define LOG_TEST(f) \
                log(__FILE__, __LINE__, \
                        __FUNCTION__, (std::ostringstream << f))

int main(int argc, char** argv) {

    LOG_TEST("HELLO");
    LOG_TEST("HELLO" << " !");

    return 0;
}

问题是我真的不知道该怎么做,因为我收到以下错误:

'std::basic_ostream::__ostream_type {aka std::basic_ostream 类型的表达式对类型 'std::stringstream& {aka std::basic_stringstream&}' 的引用的无效初始化

我不知道是否有更简单的方法可以通过 boost...

这里是来源:http ://coliru.stacked-crooked.com/view?id=222cbb23ea5162b16378b13a24fceb9e-4f0e144d2529f0880899ab58231ebbe3

4

1 回答 1

2

这里的主要问题是:(std::stringstream() << f)

如果您阅读对std::stringstream's的引用,operator<<(...)您会发现它是继承自std::ostream

http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

问题是operator<<(...)返回 an std::ostream,因此,当您传递时,(std::stringstream() << f)您实际上是将 an 传递std::ostream给需要 an 的函数std::stringstream(因此,来自 ostream 的 stringstream 的初始化无效)

要准确地实现您想要的,您必须修改宏的工作方式。尝试这样的事情:

#define LOG_TEST(f) \
    do { std::stringstream s; \
         s << f; \
         log(__FILE__, __LINE__, __FUNCTION__, s); \
    } while (0)
于 2013-04-28T01:16:29.147 回答