std::ctype<CharT>::narrow, do_narrow
來自 cppreference.com
定義於標頭檔案 <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) | |
1,2) 公有成員函式,呼叫最派生類中對應的受保護虛成員函式
do_narrow
過載。過載 (1) 呼叫 do_narrow(c, dflt),過載 (2) 呼叫 do_narrow(beg, end, dflt, dst)。3) 如果字元能夠以單位元組表示(例如,UTF-8 編碼中的 ASCII 字元是單位元組),則將(可能是寬字元)字元 c 轉換為多位元組表示。如果不存在此類轉換,則返回 dflt。
4) 對於字元陣列
[
beg,
end)
中的每個字元,將窄化字元(如果窄化失敗則為 dflt)寫入 dst 指向的字元陣列中的連續位置。對於 基本源字元集(直到 C++23)基本字元集(自 C++23 起) 中的所有字元,窄化始終成功並且始終可逆(透過呼叫 widen())。
如果窄化成功,它會保留 is() 已知的所有字元分類類別。
- 即,對於帶有
ctype<char>
facet ctc 和ctype_base::mask
值 m 的任何命名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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
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> 的公有成員函式) | |
如果可能,將寬字元縮小為單位元組窄字元 (函式) |