两相查找运算符<<问题?
Two Phase Lookup operator << issue?
我正在尝试将我自己的代码从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__ << ": "
我该如何解决这个函数?我没有找到任何可以使用this
或using
来帮助编译器的地方。
谢谢,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);
};
我认为您可以返回日志流。我不知道您的日志记录级别意味着什么,但我想在准备问题时删除了它的处理:可能有必要更改实现以适当地考虑日志记录级别。
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 呼叫运营商<<临时
- 基于boost的程序的静态链接——zlib问题