命名空间
变体
操作

std::ctype<CharT>::narrow, do_narrow

来自 cppreference.cn
< cpp‎ | locale‎ | ctype
 
 
 
 
 
定义于头文件 <locale>
public:
char narrow( CharT c, char dflt ) const;
(1)
public:

const CharT* narrow( const CharT* beg, const CharT* end,

                     char dflt, char* dst ) const;
(2)
protected:
virtual char do_narrow( CharT c, char dflt ) const;
(3)
protected:

virtual const CharT* do_narrow( const CharT* beg, const CharT* end,

                                char dflt, char* dst ) const;
(4)
1,2) 公有成员函数,调用最派生类的相应受保护虚成员函数 do_narrow 重载。重载 (1) 调用 do_narrow(c, dflt),重载 (2) 调用 do_narrow(beg, end, dflt, dst)
3) 如果字符可以用单字节表示(例如,UTF-8 编码中的 ASCII 字符是单字节),则将(可能很宽的)字符 c 转换为多字节表示。如果不存在此类转换,则返回 dflt
4) 对于字符数组 [begend) 中的每个字符,将窄化字符(或在窄化失败时使用 dflt)写入到 dst 指向的字符数组的连续位置。

对于来自 基本源字符集(C++23 前)基本字符集(C++23 起) 的所有字符,窄化总是成功的,并且总是可逆的(通过调用 widen())。

如果窄化成功,则保留 is() 已知的所有字符分类类别。

  • 即,对于任何具有 ctype<char> facet ctcctype_base::maskm 的具名 ctype 类别,is(m, c) || !ctc.is(m, do_narrow(c, dflt)) 始终为 true(除非 do_narrow 返回 dflt)。

任何数字字符的窄化都保证,如果从字符字面量 '0' 中减去结果,则差值等于原始字符的数字值。

  • 即,对于任何数字字符 c,表达式 (do_narrow(c, dflt) - '0') 的求值结果为字符的数字值。

内容

[编辑] 参数

c - 要转换的字符
dflt - 如果转换失败则生成的默认值
beg - 指向要转换的字符数组中第一个字符的指针
end - 要转换的字符数组的末尾指针之后的位置
dst - 指向要填充的字符数组的第一个元素的指针

[编辑] 返回值

1,3) 窄化字符,如果窄化失败则返回 dflt
2,4) end

[编辑] 示例

#include <iostream>
#include <locale>
 
void try_narrow(const std::ctype<wchar_t>& f, wchar_t c)
{
    char n = f.narrow(c, 0);
    if (n)
        std::wcout << '\'' << c << "' narrowed to " << +(unsigned char)n << '\n';
    else
        std::wcout << '\'' << c << "' could not be narrowed\n";
}
 
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    std::wcout.imbue(std::locale());
    std::wcout << std::hex << std::showbase << "In US English UTF-8 locale:\n";
    auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
    try_narrow(f, L'A');
    try_narrow(f, L'A');
    try_narrow(f, L'ě');
 
    std::locale::global(std::locale("cs_CZ.iso88592"));
    auto& f2 = std::use_facet<std::ctype<wchar_t>>(std::locale());
    std::wcout << "In Czech ISO-8859-2 locale:\n";
    try_narrow(f2, L'A');
    try_narrow(f2, L'A');
    try_narrow(f2, L'ě');
}

可能的输出

In US English UTF-8 locale:
'A' narrowed to 0x41
'A' could not be narrowed
'ě' could not be narrowed
In Czech ISO-8859-2 locale:
'A' narrowed to 0x41
'A' could not be narrowed
'ě' narrowed to 0xec

[编辑] 缺陷报告

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

DR 应用于 已发布行为 正确行为
LWG 126 C++98 1. 代表可逆性的代码是
do_widen(do_narrow(c), 0) == c
2. 代表类别保留的代码是
is(m, c) || !ctc.is(m, do_narrow(c), dflt)
均已更正
LWG 153 C++98 narrow 始终调用重载 (4) 调用相应的重载

[编辑] 参见

调用 do_widen
(公有成员函数) [编辑]
窄化字符
(std::basic_ios<CharT,Traits> 的公有成员函数) [编辑]
如果可能,将宽字符窄化为单字节窄字符
(函数) [编辑]