命名空间
变体
操作

std::use_facet

来自 cppreference.cn
< cpp‎ | locale
 
 
 
 
定义于头文件 <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 限定的

[编辑] 另请参阅

封装文化差异的多态刻面集
(类) [编辑]
检查区域设置是否实现了特定刻面
(函数模板) [编辑]