我正在尝试实现一个Meyers Singleton日志类,它使用'<<‘操作符来允许这样的操作:
int _tmain(int argc, TCHAR* argv[])
{
SLog& log = SLog::getLogInstance();
log << output::screen << "Test" << endl;
}是的,我知道_tmain()是一个可怕的Windows黑客-我只是想学习这些东西,这是我目前最简单的方式推动unicode;我会担心以后跨平台。
我的问题是,我的模板函数从未被调用;它似乎总是调用基本的wostream。以下是有关实现的更多信息:--SLog.h--
enum class output : int
{
screen = 0,
file,
both
};
class SLog
{
private:
TOSTREAM* m_pO;
output m_Output;
SLog(); // Private ctor; no instantiation allowed
~SLog(); // Private dtor; no way to kill it
SLog(SLog const&) {}; // Private copy ctor; copying is a no-no
SLog& operator = (SLog const&) {}; // Private - no assignations
public:
template<typename T>
TOSTREAM& operator<<(const T& statement)
{
switch (m_Output)
{
case output::file:
if( NULL != m_pO )
*m_pO << statement;
break;
case output::both:
TOUT << statement;
if( NULL != m_pO )
*m_pO << statement;
break;
default: // default to screen
TOUT << statement << " like a boss...";
break;
}
if (NULL != m_pO)
return *m_pO;
else
return TOUT;
};
TOSTREAM& operator<<(const output& statement);
static SLog& getLogInstance();
};下面是SLog.cpp:
SLog & SLog::getLogInstance()
{
static SLog log;
return log;
}
SLog::SLog()
{
m_pO = new TOSTREAM(TOUT.rdbuf());
// Initially set the output to go to the screen
m_Output = output::screen;
}
SLog::~SLog()
{
// Is our logging output stream still good?
if (NULL != m_pO)
{
m_pO->flush(); // flush it, in case there's still output
delete m_pO; // free the memory I allocated in the ctor
m_pO = NULL; // Set it to null to be sure we can't use it
}
}
TOSTREAM & SLog::operator<<(const output & statement)
{
m_Output = statement;
if (NULL != m_pO)
return *m_pO;
else
return TOUT;
}我在这里定义了TOUT、TOSTREAM等等:
#if defined(UNICODE) || defined(_UNICODE)
#define TERR std::wcerr
#define TOUT std::wcout
#define TSTRING std::wstring
#define TSSTREAM std::wstringstream
#define TOSTREAM std::wostream
#define TOFSTREAM std::wofstream
#define TNPOS std::wstring::npos
#define SPRINTF swprintf_s
#else
#define TERR std::cerr
#define TOUT std::cout
#define TSTRING std::string
#define TSSTREAM std::stringstream
#define TOSTREAM std::ostream
#define TOFSTREAM std::ofstream
#define TNPOS std::string::npos
#define SPRINTF sprintf_s
#endif添加<< " like a boss..." <<仅仅是为了查看在尝试各种方法使其打印出来时是否正在调用函数;它从未这样做,而且当我设置断点并遍历时,我只是在浏览基本的wostream实现.
所以,我显然不是我以为自己是C++程序员;我在这里做错了什么??
发布于 2015-10-23 12:47:52
似乎你忘了测试这个琐碎的情况。
log << "Test" << endl;输出
Test like a boss...如你所料。
但
log << "Test" << " more test" << endl;输出
Test like a boss... more test流插入操作符返回TOSTREAM &,因此只有第一项进入SLog。
它们应该返回一个SLog&,即*this。
SLog & SLog::operator<<(const output & statement)
{
m_Output = statement;
return *this;
}另一个操作者为了练习而离开了。
https://stackoverflow.com/questions/33302476
复制相似问题