C++之国际化(1)

  • Post author:
  • Post category:其他


转载自:

http://hi.baidu.com/nicker2010/item/8743c5a882c9d2fc14329beb

国际化(Internationalization,简写为i18n)

国际化的主要思路是以locale(地域、本土、国别)对象来代表一个可扩展的面貌集合, 以此进行地区转换工作。

Locale在C中已经有所应用,

但在C++的标准中,locale被泛化,设计得更有弹性。

事实上,C++ locale机制可以根据用户环境或者偏好进行定制,

例如可以对它进行扩展,使他能够处理时区、纸张规格等问题

C++ stream进行I/O时,所有的数值会更加locale规定的规则自动进行格式化

程序员也可以使用locale对象进行直接格式化、校勘(collation)、字符分类等工作。

string和stream中使用了char_traits


template<typename _CharT>

struct char_traits

{


typedef _CharT                                    char_type;

typedef typename _Char_types<_CharT>::int_type    int_type;

typedef typename _Char_types<_CharT>::pos_type    pos_type;

typedef typename _Char_types<_CharT>::off_type    off_type;

typedef typename _Char_types<_CharT>::state_type  state_type;


static void assign(char_type& __c1, const char_type& __c2)

{ __c1 = __c2; }


static bool eq(const char_type& __c1, const char_type& __c2)

{ return __c1 == __c2; }


static bool lt(const char_type& __c1, const char_type& __c2)

{ return __c1 < __c2; }


static int compare(const char_type* __s1, const char_type* __s2, std::size_t __n)

{  for (size_t __i = 0; __i < __n; ++__i)

if (lt(__s1[__i], __s2[__i]))

return -1;

else if (lt(__s2[__i], __s1[__i]))

return 1;

return 0;

}


static std::size_t length(const char_type* __s)

{ std::size_t __i = 0;

while (!eq(__p[__i], char_type()))

++__i;

return __i;

}


static const char_type* find(const char_type* __s, std::size_t __n, const char_type& __a)

{ for (std::size_t __i = 0; __i < __n; ++__i)

if (eq(__s[__i], __a))

return __s + __i;

return 0;

}


static char_type* move(char_type* __s1, const char_type* __s2, std::size_t __n)

{return static_cast<_CharT*>(std::memmove(__s1, __s2,

__n * sizeof(char_type)));

}


static char_type* copy(char_type* __s1, const char_type* __s2, std::size_t __n)

{ std::copy(__s2, __s2 + __n, __s1);

return __s1;

}


static char_type* assign(char_type* __s, std::size_t __n, char_type __a)

{ std::fill_n(__s, __n, __a);

return __s;

}


static char_type to_char_type(const int_type& __c)

{ return static_cast<char_type>(__c); }


static int_type to_int_type(const char_type& __c)

{ return static_cast<int_type>(__c); }


static bool eq_int_type(const int_type& __c1, const int_type& __c2)

{ return __c1 == __c2; }


static int_type eof()

{ return static_cast<int_type>(EOF); }


static int_type not_eof(const int_type& __c)

{ return !eq_int_type(__c, eof()) ? __c : to_int_type(char_type()); }

};

处理特殊字符:

如换行符(‘\n’)、EOF等

类basic_ios提供了成员函数widen(),narrow()来处理这个问题

如:


strm.widen(‘\n’);

strm.widen(‘\0’);


函数widen(),narrow()实际上使用了一个locale对象,更确切的说是该对象的ctype facet

,这个facet用来对所有字符”在char和其他表现形式之间”进行转换.