两相查找运算符<<问题?

Two Phase Lookup operator << issue?

本文关键字:lt 问题 查找 运算符      更新时间:2023-10-16

我正在尝试将我自己的代码从VS2012移植到g++4.8。

我得到这个编译错误:

AllocationManager.cpp: In member function ‘void AllocationManager::printMemoryLeaks()’:
TRLogger.h:247:42: error: ‘streamAggrator’ was not declared in this scope
 #define TRLOG_INFO streamAggrator(logINFO) << PACKET_DESCRIPTION << __FUNCTION__ << ":" << __LINE__ << ": "
                                          ^
AllocationManager.cpp:39:2: note: in expansion of macro ‘TRLOG_INFO’
  TRLOG_INFO << "sdfsn"; 

其中printMemoryLeaks是伪函数(AllocationManager未模板化):

void AllocationManager::printMemoryLeaks(void)
 {
    TRLOG_INFO << "sdfsn"; 
}

在文件TRLogger.h:中

enum TLogLevel {logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4};
class streamAggrator
{
public:
    streamAggrator(TLogLevel logLevel);
/* private: */ 
    FILELog fLog;
    WarnLog wlog;
    std::ostringstream& s1; 
    std::ostringstream& s2; 
};

template<typename T>
streamAggrator& operator<<(streamAggrator& agg, const T& obj) 
{
    agg.s1 << obj;
    agg.s2 << obj;
    agg.s2.flush();
    return agg; 
}

#define TRLOG_INFO streamAggrator(logINFO) << PACKET_DESCRIPTION << __FUNCTION__ << ":" << __LINE__ << ": "

我该如何解决这个函数?我没有找到任何可以使用thisusing来帮助编译器的地方。

谢谢,Guy

您的直接问题是试图将临时streamAggrator对象传递给通过非const引用获得streamAggrator的函数。不能将临时对象绑定到非const引用。解决此问题的方法是使输出运算符成为streamAggrator的成员:虽然不能将临时绑定到非const引用,但可以调用非const成员函数。请注意,像std::flush这样的操作程序也会遇到问题(问题是这些操作程序本身就是模板,您实际上需要一个具体的运算符来调用它们,以使编译器推导出它们的模板参数)。

很明显,我会正确地解决这个问题,也就是说,我不会试图挖掘一个不创建流的解决方案,而是创建一个std::streambuf来做实际的工作。您的示例没有做任何有用的事情,也就是说,我真的不知道您想做什么,但代码看起来非常像尝试做teestream这样的事情:写一次,但将输出发送到多个目的地。我在帖子中多次发布了相应的流缓冲区(不过主要是在Usenet上,但我认为至少在Stackoverflow上也发布过一次)。

虽然我不知道如何去掉宏来填充__FILE____LINE__,但实际的流格式化可能应该使用流缓冲区:

struct teebuf: std::streambuf {
private:
    std::streambuf* sb1;
    std::streambuf* sb2;
public:
    teebuf(std::streambuf* sb1, std::streambuf* sb2): sb1(sb1), sb2(sb2) {}
    int overflow(int c) {
        this->sb1->sputc(c);
        this->sb2->sputc(c);
        return std::char_traits<char>::not_eof(c);
    }
    int sync() {
        this->sb1->pubsync();
        this->sb2->pubsync();
    }
};
class logstream
    : std::ostream {
    std::ofstream out;
    teebuf        sbuf;
public:
    logstream()
        : out("file.log")
        , sbuf(out.rdbuf(), std::clog.rdbuf()) {
        this->init(&this->sbuf);
    }
    logstream(logstream&& other)
        : out(std::move(other.out))
        , sbuf(std::move(other.sbuf)) {
        this->init(&this->sbuf);
};

我认为您可以返回日志流。我不知道您的日志记录级别意味着什么,但我想在准备问题时删除了它的处理:可能有必要更改实现以适当地考虑日志记录级别。