string_view格式流输出的实现

Implementation of string_view formatted stream ouput

本文关键字:输出 实现 格式 view string      更新时间:2023-10-16

在实现c++ 1z的std::basic_string_view以在较旧的编译器上使用它时,我遇到了它的流输出操作符过载的问题。基本上,它必须输出由string_view引用的内容,而不依赖于任何空终止符存在(因为string_view不保证为空终止符)。

通常,为operator<<编写重载是相当容易的,因为您可以依赖已经存在的重载,因此不需要像在SO上提到的那样使用哨兵对象。

但是在这种情况下,没有预定义的重载operator<<接受字符指针和长度(显然)。因此,我在当前的实现中创建了一个临时的std::string实例:

template< typename TChar, typename TTraits >
auto operator<<(::std::basic_ostream<TChar, TTraits>& p_os, basic_string_view<TChar, TTraits> p_v)
    -> ::std::basic_ostream<TChar, TTraits>&
{
    p_os << p_v.to_string(); // to_string() returns a ::std::string.
    return p_os;
}

这可以工作,但是我真的不喜欢我必须创建一个临时的std::string实例,因为这需要冗余复制数据和潜在的动态内存的使用。至少在我看来,这违背了使用轻量级引用类型的目的。

我的问题是:

什么是最好的方法来实现正确的格式化输出为我的string_view没有开销?


在研究的过程中,我发现LLVM是这样做的:(在这里找到)

// [string.view.io]
template<class _CharT, class _Traits>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __os, basic_string_view<_CharT, _Traits> __sv)
{
    return _VSTD::__put_character_sequence(__os, __sv.data(), __sv.size());
}

__put_character_sequence的实现驻留在这个文件中,但是它大量使用内部函数来进行格式化。我需要自己重新实现所有格式吗?

据我所知,你必须自己处理这件事。

幸运的是,您需要为类似字符串的项做的格式化是相当少的——如果需要,主要是在字符串之前或之后插入填充。

  • 要确定是否需要填充,您需要使用ios_base::width()检索流的当前字段。
  • 要弄清楚是否在您写出字符串之前或之后插入该字符串,您需要使用ios_base::fmtflags()检索左/右标志。
  • 要确定要插入什么作为填充,可以调用ios_base::fill()
  • 最后,我相信你需要检查fixed标志-如果内存服务,设置它,你需要截断你的字符串,如果它比当前字段的宽度长。

因此(使用string_view的超简化实现),代码可能看起来像这样:

#include <iostream>
#include <iomanip>
#include <ios>
#include <sstream>
class string_view { 
    char const *data;
    size_t len;
public:
    string_view(char const *data, size_t len) : data(data), len(len) {}
    friend std::ostream &operator<<(std::ostream &os, string_view const &sv) { 
        std::ostream::sentry s{ os };
        if (s) {
            auto fill = os.fill();
            auto width = os.width();
            bool left = os.flags() & std::ios::left;
            bool right = os.flags() & std::ios::right;
            bool fixed = os.flags() & std::ios::fixed;
            auto pad = [&](size_t width) { while (width--) os.put(fill); };
            if (sv.len < width) {
                auto padding_len = width - sv.len;
                if (right) pad(padding_len);
                os.write(sv.data, sv.len);
                if (left) pad(padding_len);
            }
            else {
                os.write(sv.data, fixed ? width : sv.len);
            }
        }
        os.width(0);
        return os;
    }
};
#ifdef TEST   
void check(std::stringstream &a, std::stringstream &b) {
    static int i;
    ++i;
    if (a.str() != b.str()) {
        std::cout << "Difference in test:" << i << "n";
        std::cout << """ << a.str() << ""n";
        std::cout << """ << b.str() << ""n";
    }
    a.seekp(0);
    b.seekp(0);
}
int main() { 
    char string[] = "Now is the time for every good man to come to the aid of Jerry.";
    std::stringstream test1;
    std::stringstream test2;
    test1 << string_view(string, 3);
    test2 << std::string(string, 3);
    check(test1, test2);
    test1 << string_view(string + 4, 2);
    test2 << string_view(string + 4, 2);
    check(test1, test2);
    test1 << std::setw(10) << std::left << string_view(string, 6);
    test2 << std::setw(10) << std::left << std::string(string, 6);
    check(test1, test2);
    test1 << std::setw(10) << std::right << string_view(string, 6);
    test2 << std::setw(10) << std::right << std::string(string, 6);
    check(test1, test2);
    test1 << std::setw(10) << std::right << string_view(string, sizeof(string));
    test2 << std::setw(10) << std::right << std::string(string, sizeof(string));
    check(test1, test2);
    test1 << std::setw(10) << std::right << std::fixed << string_view(string, sizeof(string));
    test2 << std::setw(10) << std::right << std::fixed << std::string(string, sizeof(string));
    check(test1, test2);
}
#endif

哦,还有一个细节。由于我们只是写入流,而不是直接写入底层缓冲区,我认为在这种情况下,我们可能实际上不需要创建sentry对象。如图所示,创建和使用它非常简单,但毫无疑问,删除它至少会快一点。

在我看来,您应该能够让您的插入操作符依赖于std::ostream::write。比如:

template<class _CharT, class _Traits>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __os, basic_string_view<_CharT, _Traits> __sv)
{
    __os.write(__sv.data(), __sv.size());
    return __os;
}