c++11 标准模板(STL)(std::locale)(三)替换 locale

用以封装文化差异的多态刻面的集合


std::locale 类型对象是不可变平面的不可变索引集。 C++ 输入/输出库的每个流对象与一个 std::locale 对象关联,并用其平面分析及格式化所有数据。另外, locale 对象与每个 std::basic_regex 对象关联。 locale 对象亦可在标准容器和算法中用作进行字符串对照的谓词,而且能被直接访问,以获得或修改其所保有的平面。

C++ 程序中构造的每个 locale 至少保有下列标准平面,但程序可以定义额外特化,或全新的平面,并将它们添加到任何既存的 locale 对象。

替换 locale

std::locale::operator=

const locale& operator=( const locale& other ) throw();

(C++11 前)

const locale& operator=( const locale& other ) noexcept;

(C++11 起)

创建 other 的副本,替换 *this 的内容。增加 other 所保有的所有平面的引用计数。减少 *this 先前所保有的所有平面的引用计数,并删除引用计数成为零的平面。

返回值

返回 *this ,它现在是 other 的副本。

调用示例

#include <iostream>
#include <locale>
#include <codecvt>

struct myfacet : std::locale::facet
{
    myfacet(std::size_t refs = 0) : facet(refs) {}
    static std::locale::id id;
};

//类 std::locale::id 提供本地环境片面的实现限定标识。
std::locale::id myfacet::id;

int main()
{
    std::locale locale1("Chinese (Simplified)_China.936"); // locale2 为本地环境
    std::cout << "locale1.name():   " << locale1.name() << std::endl;

    //创建 other 的副本,替换 *this 的内容。增加 other 所保有的所有平面的引用计数。
    std::locale locale2 = locale1;
    std::cout << "locale2.name():   " << locale2.name() << std::endl;
    return 0;
}

输出

locale1.name():   Chinese (Simplified)_China.936
locale2.name():   Chinese (Simplified)_China.936

以复制自另一 locale 的编译时鉴别的平面构造 locale

std::locale::combine

template< class Facet >
locale combine( const locale& other ) const;

构造 locale 对象,结果为 *this 的副本,除了 Facet 类型平面复制自 other

返回值

新的无名 locale 。

异常

other 不实装 Facet 则为 std::runtime_error 。

调用示例

#include <iostream>
#include <locale>
#include <codecvt>

struct myfacet : std::locale::facet
{
    myfacet(std::size_t refs = 0) : facet(refs) {}
    static std::locale::id id;
};

//类 std::locale::id 提供本地环境片面的实现限定标识。
std::locale::id myfacet::id;

int main()
{
    const double number = 1000.25;
    std::cout << "\"C\" locale: " << number << std::endl;
    std::locale locale1("English_US.1251"); // locale1 为本地环境
    std::cout << "locale1.name():   " << locale1.name() << std::endl;
    std::locale locale2 = std::locale().combine<std::numpunct<char>>(locale1);
    std::cout.imbue(locale2);
    std::cout << "\"C\" locale with English_US.1251 numpunct: " << number << std::endl;

    return 0;
}

输出

"C" locale: 1000.25
locale1.name():   English_United States.1251
"C" locale with English_US.1251 numpunct: 1,000.25

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值