std::use_facet
來自 cppreference.com
定義於標頭檔案 <locale> |
||
template< class Facet > const Facet& use_facet( const std::locale& loc ); |
||
獲取由 loc 實現的 facet 的引用。
如果 Facet 不是一個 facet,其定義包含公共靜態成員 id
,或者它是一個 volatile-qualified 的 facet,則程式是非良構的。
目錄 |
[編輯] 引數
loc | - | 要查詢的區域設定物件 |
[編輯] 返回值
返回 facet 的引用。此函式返回的引用只要有任何 std::locale 物件引用該 facet,就有效。
[編輯] 異常
如果 std::has_facet<Facet>(loc) == false,則丟擲 std::bad_cast。
[編輯] 注意
如果從 use_facet
獲取的 Facet
物件的引用在語句結束之後仍被使用,則 std::locale 物件不應是臨時的。
// BAD: auto& f = std::use_facet<std::moneypunct<char, true>>(std::locale{"no_NO.UTF-8"}); foo(f.curr_symbol()); // Error: f internally uses a dangling reference // to a std::locale object that no longer exists. // GOOD: auto loc = std::locale{"is_IS.UTF-8"}; // OK: a non-temporary object auto& f = std::use_facet<std::moneypunct<char, true>>(loc); foo(f.curr_symbol()); // OK: f internally uses a reference to existing locale object.
[編輯] 示例
顯示使用者首選區域設定所使用的 3 字母貨幣名稱。
執行此程式碼
#include <iostream> #include <locale> int main() { for (const char* name: {"en_US.UTF-8", "de_DE.UTF-8", "en_GB.UTF-8"}) std::cout << "Your currency string is " << std::use_facet<std::moneypunct<char, true>>(std::locale{name}). curr_symbol() << '\n'; }
輸出
Your currency string is USD Your currency string is EUR Your currency string is GBP
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 31 | C++98 | 返回的引用保持可用 只要區域設定值本身存在 |
返回的引用保持可用 只要某個區域設定物件引用該 facet |
LWG 38 | C++98 | Facet 不被要求具有直接成員 id |
需要 |
LWG 436 | C++98 | 尚不清楚 Facet 是否可以 cv 限定 |
它可以是 const 限定的,但不能是 volatile 限定的 |
[編輯] 另請參閱
封裝文化差異的多型刻面集 (類) | |
檢查區域設定是否實現了特定刻面 (函式模板) |