我正在尝试实施一个使用'<<<<<<<<<<<<<&#运营商允许这样的事情:
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 ++程序员;我在这做错了什么?
答案 0 :(得分:2)
似乎你忘记了测试那些琐碎的案例。
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;
}
另一名经营者离开时作为练习。