我的C++ traits学习笔记,这是第一篇。
刚刚接触traits技术,很多地方不知道理解的对还是不对,有路过的朋友如果发现问题请不吝指教,谢了!
翻译文章怪不容易的,转载请注明出处http://www.cnblogs.com/youthlion/archive/2011/12/01/2255618.html,再次感谢!
资料(a)
http://en.wikipedia.org/wiki/Traits_class
a traits class is a class template used to associate information or behaviour to a compile-time entity, typically a data type or a constant, without modifying the existing entity. In the C++ programming language, this is normally achieved by defining a primary class template, and creating explicit or partial specializations for the relevant types.
traits class是个类模板,在不修改一个实体(通常是数据类型或常量)的前提下,把属性和方法关联到一个编译时的实体。在c++中的具体实现方式是:首先定义一个类模板,然后进行显式特化或进行相关类型的部分特化。
我的理解是:traits是服务于泛型编程的,其目的是让模板更加通用,同时把一些细节向普通的模板用户隐藏起来。当用不同的类型去实例化一个模板时,不可避免有些类型会存在一些与众不同的属性,若考虑这些特性的话,可能会导致形成的模板不够“泛型”或是过于繁琐,而traits的作用是把这些特殊属性隐藏起来,从而实现让模板更加通用。
资料(b)
traits class技术最初似乎是Nathan C. Myers提出来的,这是他在1995年关于traits class的文章。草草地翻译一下:
问题描述:
ANSI/ISO C++标准库工作组那伙大牛在搞标准库对国际化的支持的时候遇到了问题。
比如,在iostream这个库里,steambuf的接口依赖于EOF,而EOF与所有字符类型都不同,在传统的库里,EOF为int,读取字符的那些函数的返回值也是整型:
2: ...
// return the next character, or EOF.
// get N characters.
5: };