Traits

Traits

Use of traits is another common programming technique in conjunction with template programming. A traits class is a shadow class that accompanies another type and contains information that is associated with the other type.

The standard C++ library has several examples of traits: the character traits are an example. As you might know the standard string class is a class templates that is parameterized on the character type in order to allow for representation of tiny character and wide character string, at least. In principle, the string class template, which is actually named basic_string, can be instantiated on any character type, not just the two character type that are predefined by the C++ language. If for instance someone needs to represent, say Japanese, characters as a structure named Jchar, then the basic_string template can be used to create a string class for Japanese characters, namely basic_string<Jchar>.

Imagine you are implementing such a string class template? You would find that there is information that you would need, but that is not contained in the character type. For instance, how would you calculate the string length? By counting all characters in the string until you find the end-of-string character. How would you know which is the end-of-string character? Okay, we know it is '\0' in the case of tiny characters of type char, and there is a corresponding end-of-string character defined for characters of type wchar_t, but how would you identify the end-of-string character for Japanese characters of type Jchar? Quite obviously the information about the end-of-string character is a piece of information that is associated with each character type, but is not contained in the character type. And this is exactly what traits are for: they provide information that is associated with a type, but is not contained in the type.

A traits type is a shadow type, typically a class template that can be instantiated or specialized for a group of types and provides information associated with each type. The character traits for instance, see the char_traits class template in the standard C++ library, contains a static character constant that designates the end-of-string character for the character type it is instantiated for.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值