std::locale::locale

来自cppreference.com
< cpp‎ | locale‎ | locale
定义于头文件 <locale>
(1)
locale() throw();
(C++11 前)
locale() noexcept;
(C++11 起)
(2)
locale( const locale& other ) throw();
(C++11 前)
locale( const locale& other ) noexcept;
(C++11 起)
explicit locale( const char* std_name );
(3)
explicit locale( const std::string& std_name );
(4) (C++11 起)
locale( const locale& other, const char* std_name, category cat );
(5)
locale( const locale& other, const std::string& std_name, category cat );
(6) (C++11 起)
template< class Facet >
locale( const locale& other, Facet* f );
(7)
locale( const locale& other, const locale& one, category cat );
(8)

构造新的 locale 对象。

1) 默认构造函数。构造全局 C++ 本地环境的副本,它是最近用作 std::locale::global 的参数的 locale ,或若未曾调用 std::locale::global 则为 std::locale::classic 的副本。
2) 复制构造函数。构造 other 的副本。
3-4) 构造拥有特定 std_name 的系统本地环境(如 "C" 或 "POSIX" 或 "en_US.UTF-8" 或 "English_US.1251" )的副本,若操作系统支持这种本地环境。以此方式构造的 locale 拥有名称。
5-6) 构造 other 的副本,除了 cat 参数所鉴别的所有平面,这些平面从其 std_name 所标识的系统本地环境复制。以此方式构造的 locale 拥有名称,当且仅当 other 拥有名称。
7) 构造 other 的副本,除了 Facet 类型平面(典型地从实参类型推导),该平面从参数 facet 安装。若 facet 为空指针,则构造的 locale 为 other 的完整副本。以此方式构造的 locale 无名称。
8) 构造 other 的副本,除了 cat 参数所鉴别的所有平面,这些平面从 one 复制。若 otherone 都拥有名称,则产生的 locale 拥有名称。

参数

other - 要复制的另一 locale
std_name - 要使用的系统本地环境名称
f - 指向要与 other 合并的平面的指针
cat - 用于鉴别要与 other 合并的平面的 locale::category
one - 接收平面来源的另一 locale

异常

3,5) 若操作系统无名为 std_name 的本地环境,或若 std_name 为空指针则为 std::runtime_error
4,6) 若操作系统无名为 std_name 的本地环境则为 std::runtime_error
7,8) 可能抛出实现定义的异常。

注解

典型地以直接获得自 new 表达式的参数 f 为第二参数调用重载 7 : locale 负责从其自身的析构函数调用匹配的 delete

示例

#include <codecvt>
#include <iostream>
#include <locale>
 
std::ostream& operator<< (std::ostream& os, std::locale const& loc)
{
    if (loc.name().length() <= 80) { return os << loc.name() << '\n'; }
 
    for (const auto c : loc.name())
    {
        c != ';' ? os << c : os << "\n    ";
    }
    return os << '\n';
}
 
int main()
{
    std::locale l1; 
        // l1 为经典 "C" 本地环境副本
    std::locale l2("en_US.UTF-8");
        // l2 为 Unicode 本地环境
    std::locale l3(l1, l2, std::locale::ctype);
        // l3 为 "C" ,除了 ctype 为 Unicode
    std::locale l4(l1, new std::codecvt_utf8<wchar_t>);
        // l4 为 "C" ,除了 codecvt
    std::cout
        << "Locale names:\n"
        << "l1: " << l1 << "l2: " << l2
        << "l3: " << l3 << "l4: " << l4;
}

可能的输出:

Locale names:
l1: C
l2: en_US.UTF-8
l3: LC_CTYPE=en_US.UTF-8
    LC_NUMERIC=C
    LC_TIME=C
    LC_COLLATE=C
    LC_MONETARY=C
    LC_MESSAGES=C
    LC_PAPER=C
    LC_NAME=C
    LC_ADDRESS=C
    LC_TELEPHONE=C
    LC_MEASUREMENT=C
    LC_IDENTIFICATION=C
l4: *

参阅

析构 locale 和其引用计数变为零的平面
(公开成员函数)