std::ctype<CharT>:: narrow, do_narrow
|
定义于头文件
<locale>
|
||
|
public
:
char narrow ( CharT c, char dflt ) const ; |
(1) | |
|
public
:
const
CharT
*
narrow
(
const
CharT
*
beg,
const
CharT
*
end,
|
(2) | |
|
protected
:
virtual char do_narrow ( CharT c, char dflt ) const ; |
(3) | |
|
protected
:
virtual
const
CharT
*
do_narrow
(
const
CharT
*
beg,
const
CharT
*
end,
|
(4) | |
do_narrow
重载。重载 (1) 调用
do_narrow
(
c, dflt
)
,重载 (2) 调用
do_narrow
(
beg, end, dflt, dst
)
。
[
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 | - | 指向待填充字符数组首个元素的指针 |
返回值
示例
#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>
的公开成员函数)
|
|
|
若可能则将宽字符窄化为单字节窄字符
(函数) |