【发布时间】:2010-12-28 19:27:06
【问题描述】:
我正在为我的一个班级实施stream insertion operator。我希望我的班级能够处理窄流和宽流。我正在使用模板来允许这种行为——除了字符文字之外,一切都与实际使用的流类型无关。如果是宽字符串,字符文字需要在文字前面加上L,否则不需要。
有没有办法将这种东西键入模板参数,这样我就不需要在这上面复制太多代码了?
(如果可能,我宁愿避免在运行时执行窄到宽字符或宽到窄字符的转换。)
我目前拥有的示例——它是一个模板,但由于宽字符文字,它不适用于窄字符流:
template <typename charT, typename traits>
std::basic_ostream<charT, traits>& operator<<(
std::basic_ostream<charT, traits>& lhs,
const Process& rhs
)
{
lhs << L"Process (0x" << std::setw(8) << std::hex
<< std::setfill(L'0') << rhs.GetId() << L") ";
lhs << rhs.GetName() << std::endl;
lhs << L"Command Line: " << rhs.GetCmdLine() << std::endl;
const std::vector<Thread>& threads = rhs.GetThreads();
for (std::vector<Thread>::const_iterator it = threads.begin();
it != threads.end(); ++it)
{
lhs << L" --> " << *it << std::endl;
}
const std::map<void *, Module>& modules = rhs.GetModules();
for (std::map<void *, Module>::const_iterator it = modules.begin();
it != modules.end(); ++it)
{
lhs << L" --> " << it->second << std::endl;
}
return lhs;
}
【问题讨论】:
-
当有无数新字符类型出现时,在 C++0x 中会更有趣。
-
刚好遇到同样的问题,我暂时选择了dalle的解决方案。现在,在 2015 年使用 c++0x 甚至 c++11,我很好奇是否有更好的方法来解决这个问题。我只是尝试进入流...
-
@AndreasW.Wylach:我刚刚放弃并在 Fastformat 的 API 的启发下构建了自己的东西:github.com/BillyONeal/Instalog/blob/master/LogCommon/…
-
@AndreasW.Wylach:示例使用:github.com/BillyONeal/Instalog/blob/master/LogCommon/…
标签: c++ templates unicode iostream