您的位置:首页 > 大数据 > 人工智能

char_traits struct 初步学习

2014-12-22 15:33 106 查看
在学习文件读取时碰到文件尾字符 EOF 的问题,顺藤摸瓜找到 char_traits

msdn 上关于
EOF 的说明,就一句话:

Returns the end-of-file (EOF) character.

在注意中提到一句:

A value that represents end of file (such as EOF or WEOF).

意思是 EOF 表示的是文件尾的一个值,对于不同的字符集会对应不同的数值,但对用户来说就隐藏了这种细节。在给出的示例中也说明了这一点:

// char_traits_eof.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main()
{
using namespace std;

char_traits<char>::char_type ch1 = 'x';
char_traits<char>::int_type int1;
int1 = char_traits<char>::to_int_type(ch1);
cout << "char_type ch1 is '" << ch1 << "' and corresponds to int_type "
<< int1 << "." << endl << endl;

char_traits<char>::int_type int2 = char_traits<char>::eof();
cout << "The eof marker for char_traits<char> is: " << int2 << endl;

char_traits<wchar_t>::int_type int3 = char_traits<wchar_t>::eof();
cout << "The eof marker for char_traits<wchar_t> is: " << int3 << endl;
}输出:
char_type ch1 is 'x' and corresponds to int_type 120.

The eof marker for char_traits<char> is: -1
The eof marker for char_traits<wchar_t> is: 65535

可以看到 char_traits 是模板类,在 cplusplus 上给出的解释是:
Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters.

就是说 character traits 实例化了字符的各种性质(包括 eof 的数值,int_type, off_type, pos_type, state_type 等的 typedef),并提供对某些在字符和字符序列上特定操作的语义(语法?)。

简而言之,就是其中的 char_traits<char> 既是对字符集的实例化。

msdn 上给出的说明

template <
class CharType
> struct char_traits;

The char_traits struct describes attributes associated with a character.
The template struct describes various character traits for type CharType. The template class basic_string as well as several iostream template classes, including basic_ios, use this information to manipulate elements of type CharType.

模板构造描述了 CharType 类型的各种特性,得到这种类型特性之后,就可以用这些信息来操作 CharType 类的元素。

还有相关博文:

char_traits

摘要:c++标准库中,有一个string,这个相信大家都知道,其实它是一个basic_string的一个typedef,其实在 msdn 这些地方,查 string 查不到什么太多东西,需要了解内部接口,得查basic_string

至于char_traits,是base_string的一个模板参数,它主要负责关于字符的属性和方法,譬如 eq、lt、compare、find 这些,比较字符大小,查找字符等等,这个类有什么用呢?

可以重载来改变string的一些字符相关的内部属性,譬如大小写敏感、字符串比较这些,具体的接口,而且,里面的接口基本上都是 static ,可以类似 strcpy、strlen 这样的接口直接使用(这个好像意义不大:P)

C++的Char traits模板类

摘要:字符特性模板,目的是提供最基本的字符特性的统一的方法函数。

C++ traits学习笔记(一)

摘要:traits是服务于泛型编程的,其目的是让模板更加通用,同时把一些细节向普通的模板用户隐藏起来。当用不同的类型去实例化一个模板时,不可避免有些类型会存在一些与众不同的属性,若考虑这些特性的话,可能会导致形成的模板不够“泛型”或是过于繁琐,而traits的作用是把这些特殊属性隐藏起来,从而实现让模板更加通用。

如有错误,恳请指正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐