Namespaces
Variants

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

From cppreference.net
定义于头文件 <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) 将(可能为宽字符的)字符 c 转换为多字节表示形式,前提是该字符可以用单字节表示(例如,UTF-8编码中的ASCII字符为单字节)。如果不存在此类转换,则返回 dflt
4) 对于字符数组 [ beg , end ) 中的每个字符,将窄化字符(当窄化失败时则使用 dflt )写入到由 dst 指向的字符数组的连续位置。

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

窄化转换若成功,将保留所有 is() 已知的字符分类类别。

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

任何数字字符的窄化保证:若从字符字面量 '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++标准。

缺陷报告 应用于 发布时行为 正确行为
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> 的公开成员函数)
若可能则将宽字符窄化为单字节窄字符
(函数)