命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | locale‎ | codecvt
 
 
 
 
 
定义于头文件 <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) 尝试转换由 [fromfrom_end) 定义的字符数组中的 ExternT 字符,给定初始转换状态 state,最多转换为 maxInternT 字符,并返回此转换将消耗的 ExternT 字符数。修改 state,如同执行 do_in(state, from, from_end, from, to, to + max, to) 对于某个假想的 [toto + max) 输出缓冲区。

目录

[edit] 返回值

如果通过 do_in() 转换,直到所有 from_end - from 字符被消耗,或者生成 maxInternT 字符,或者发生转换错误,则将消耗的 ExternT 字符数。

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

[edit] 示例

#include <iostream>
#include <locale>
#include <string>
 
int main()
{
    using facet_type = std::codecvt<wchar_t, char, std::mbstate_t>;
 
    // narrow multibyte encoding
    std::string s = "z\u00df\u6c34\U0001d10b"; // or u8"zß水𝄋"
              // or "\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

[edit] 缺陷报告

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

DR 应用于 已发布行为 正确行为
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)
不是必需的

[edit] 参见

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