Namespaces
Variants

std::codecvt<InternT,ExternT,StateT>:: out, do_out

From cppreference.net
定义于头文件 <locale>
public :

result out ( StateT & state,
const InternT * from,
const InternT * from_end,
const InternT * & from_next,
ExternT * to,
ExternT * to_end,

ExternT * & to_next ) const ;
(1)
protected :

virtual result do_out ( StateT & state,
const InternT * from,
const InternT * from_end,
const InternT * & from_next,
ExternT * to,
ExternT * to_end,

ExternT * & to_next ) const ;
(2)
1) 公开成员函数,调用最派生类的成员函数 do_out
2) 若此 codecvt facet 定义了转换规则,则将源范围 [ from , from_end ) 中的内部字符转换为外部字符,并将结果存入从 to 开始的后续位置。转换的内部字符数不超过 from_end - from ,写入的外部字符数不超过 to_end - to 。转换完成后, from_next to_next 将指向最后一个成功转换元素之后的位置。

如果此 codecvt facet 未定义转换,则不会转换任何字符。 to_next 将被设置为等于 to state 保持不变,并返回 std::codecvt_base::noconv

do_out ( state, from, from + 1 , from_next, to, to_end, to_next ) 必须返回 ok ,如果

  • codecvt 转换刻面被 basic_filebuf 所使用,且
  • do_out ( state, from, from_end, from_next, to, to_end, to_next ) 会在 from ! = from_end 时返回 ok

目录

返回值

类型为 std::codecvt_base::result 的值,用于指示成功状态如下:

ok 转换完成
partial 输出缓冲区空间不足或源缓冲区意外结束
error 遇到无法转换的字符
noconv 此facet为非转换类型,未写入任何输出

非转换特化 std:: codecvt < char , char , std:: mbstate_t > 始终返回 std::codecvt_base::noconv

注释

要求满足 from <= from_end && to <= to_end ,且 state 要么表示初始移位状态,要么通过转换序列中前序字符获得。

虽然 codecvt 支持N:M转换(例如UTF-16到UTF-8转换,可能需要两个内部字符来决定输出哪些外部字符),但 std::basic_filebuf 只能使用定义1:N转换的 codecvt facet,也就是说在写入文件时必须能够一次处理一个内部字符。

在进行N:M转换时,此函数可能在消耗完所有源字符后返回 std::codecvt_base::partial from_next == from_end )。这意味着需要另一个内部字符才能完成转换(例如,当从UTF-16转换到UTF-8时,若源缓冲区中的最后一个字符是高代理项)。

state 的影响被有意规定为未指定。在标准 facet 中,它用于维护移位状态,例如调用 std:: wcsrtombs 时的情况,因此会被更新以反映最后一个成功转换字符后的移位状态,但用户定义的 facet 可以自由使用它来维护任何其他状态,例如计算遇到的特殊字符数量。

示例

#include <iostream>
#include <locale>
#include <string>
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    auto& f = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(std::locale());
    std::wstring internal = L"z\u00df\u6c34\U0001f34c"; // L"zß水🍌"
    // 注意以下操作也可通过 wstring_convert 实现
    std::mbstate_t mb{}; // 初始移位状态
    std::string external(internal.size() * f.max_length(), '\0'); 
    const wchar_t* from_next;
    char* to_next;
    f.out(mb, &internal[0], &internal[internal.size()], from_next,
              &external[0], &external[external.size()], to_next);
    // 为简洁起见省略了错误检查
    external.resize(to_next - &external[0]);
    std::cout << "The string in narrow multibyte encoding: " << external << '\n';
}

输出:

The string in narrow multibyte encoding: zß水🍌

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 76 C++98 未明确说明转换是否需要
支持每次处理一个内部字符
仅在由 basic_filebuf
使用时需要

参见

[virtual]
将字符从输出区写入关联文件
( std::basic_filebuf<CharT,Traits> 的虚受保护成员函数)
将宽字符串转换为字节字符串
( std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc> 的公开成员函数)
根据给定状态将宽字符串转换为窄多字节字符串
(函数)
[virtual]
将字符串从 ExternT 转换为 InternT ,例如从文件读取时
(虚受保护成员函数)