std::use_facet
来自 cppreference.cn
定义于头文件 <locale> |
||
template< class Facet > const Facet& use_facet( const std::locale& loc ); |
||
获取由 loc 实现的 facet 的引用。
如果 Facet 不是 facet,且其定义不包含公共静态成员 id
,或者它是 volatile 限定的 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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 31 | C++98 | 返回的引用保持可用 只要区域设置值本身存在 |
返回的引用保持可用,只要 只要某些区域设置对象引用该 facet |
LWG 38 | C++98 | 不要求 Facet 具有直接成员 id |
要求 |
LWG 436 | C++98 | 不清楚 Facet 是否可以是 cv 限定的 |
可以是 const 限定的,但不能是 volatile 限定的 |
[编辑] 参见
封装文化差异的多态 facet 集合 (类) | |
检查区域设置是否实现了特定的 facet (函数模板) |