【发布时间】:2011-08-09 12:33:06
【问题描述】:
我目前正在使用非常聪明的包boost::const_string,直到http://libcxx.llvm.org/ 可以在Ubuntu 或GCC 上预先打包,使其__versa_string(在标题ext/vstring.h)成为默认字符串实现。 libcxx 的 std::string 以及 __versa_string 默认使用 _small-string 优化 (SSO)。但是,缺少对输出到 std::ostream 的默认支持。代码
#include <iostream>
#include <boost/const_string.hpp>
const_string<char> x;
std::cout << x << endl;
除非我们通过 c_str() 将 x 强制转换为 c 字符串,否则它不起作用
std::cout << x.c_str() << endl;
它可以按预期编译和工作。我将以下行添加到const_string.hpp
template <typename T>
inline std::ostream & operator << (std::ostream & os, const boost::const_string<T> & a)
{
return os.write(a.data(), a.size());
}
这应该比x.c_str() 提高性能,因为size() 是已知的,不需要像c_str() 那样通过搜索NULL 来计算。我为我工作,但我不确定它是否适用于所有情况。我错过了什么吗?
【问题讨论】:
-
这取决于你想要的不可打印字符的行为(尤其是
\0),我猜。我认为(!)普通字符串的默认行为是在空字符后截断。你的实现可能不会那样做。顺便说一下,+1 让我知道boost::const_string。 -
我认为这是一种权衡。据我所知,您的代码没有反映像
std::setw这样的操纵器设置。如果你不使用const_string的那些操纵器,我认为你的代码有它自己的用途。
标签: c++ templates string boost ostream