Namespaces
Variants

std::codecvt<InternT,ExternT,StateT>:: length, do_length

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

int length ( StateT & state, const ExternT * from, const ExternT * from_end,

std:: size_t max ) const ;
(1)
protected :

virtual int do_length ( StateT & state, const ExternT * from, const ExternT * from_end,

std:: size_t max ) const ;
(2)
1) 公开成员函数,调用最派生类的成员函数 do_length
2) 尝试将定义在 [ from , from_end ) 字符数组中的 ExternT 字符进行转换(给定初始转换状态 state ),最多生成 max InternT 字符,并返回此转换将消耗的 ExternT 字符数量。修改 state 的方式类似于对某个虚拟的 [ to , to + max ) 输出缓冲区执行 do_in ( state, from, from_end, from, to, to + max, to ) 操作。

目录

返回值

如果通过 do_in() 进行转换,将消耗的 ExternT 字符数量,直到以下任一情况发生:所有 from_end - from 字符被消耗完毕,或已生成 max InternT 字符,或出现转换错误。

非转换特化 std:: codecvt < char , char , std:: mbstate_t > 返回 std:: min ( max, from_end - from )

示例

#include <iostream>
#include <locale>
#include <string>
int main()
{
    using facet_type = std::codecvt<wchar_t, char, std::mbstate_t>;
    // 窄字符多字节编码
    std::string s = "z\u00df\u6c34\U0001d10b"; // 或 u8"zß水𝄋"
              // 或 "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"
    std::locale loc("en_US.UTF-8");
    facet_type const& codecvt_facet = std::use_facet<facet_type>(loc);
    std::mbstate_t mb = std::mbstate_t();
    std::cout << "Only the first "
              << codecvt_facet.length(mb, s.data(), s.data() + s.size(), 2)
              << " bytes out of " << s.size() << " would be consumed"
                 " to produce the first 2 characters\n";
}

输出:

Only the first 3 bytes out of 10 would be consumed to produce the first 2 characters

缺陷报告

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

缺陷报告 适用标准 发布时行为 正确行为
LWG 75 C++98 未指定对 state 的影响 已指定
LWG 305 C++98 std::codecvt<wchar_t, char, std::mbstate_t>::do_length
被要求返回 std:: min ( max, from_end - from )
不作要求

参见

[virtual]
将字符串从 ExternT 转换为 InternT ,例如从文件读取时
(虚受保护成员函数)