adamsun 2004年04月02日


下面是从boost members中的Rob Stewart的邮件中摘过来的

Trait - A class template parameterized on a single type that
associates information with that type. A traits class,
therefore, provides an external, named grouping of
metainformation, behavior, or both for that type. A trait class
is never passed as a template parameter; it's name is ubiquitous.
A traits class never has state.

Policy - A class template passed to other templates for the
purpose of providing a named grouping of metainformation,
behavior, or both to those templates. Because it is a template
parameter, different policy classes can be used as desired. In
many cases, a policy class is used as a base class.

下面是从boost members中的Mark Rodgers的完整邮件

Well I think in terms of code, and it really is quite simple IMHO:

Traits look like this:

template< typename T >
class SomeTraits
// Stuff that tells us about T

and Policies look like this

template< typename Policy >
class SomeThing
// Delegates some behaviour to Policy

IOW, traits are class templates and policies are template parameters so
there really can't be any confusion between the two. So in the case

template<class charT, class traits = char_traits<charT>,
class Allocator = allocator<charT> >
class basic_string {

"char_traits" is a traits class template but "traits" is actually a policy
template parameter. It is quite reasonable for specialisations of traits
templates to be used as arguments to policy parameters, which is exactly
what happens when we write

std::basic_string< char,std::char_traits<char> >

But I don't think there is anything in basic_string that requires the
template argument to be a specialisation of a class template. I think it
would be quite legitimate to write

class MyFunkyCharBehaviour { /*...*/ };
typedef std::basic_string<char,MyFunkyCharBehaviour> MyFunkyString;

so the "traits" parameter is indeed misnamed.

However std::char_traits is most definitely a traits template and doesn't
*have* to be used as a policy. In fact std::basic_string could have been
written to exclusively use char_traits *instead* of a policy.


52 点赞 收藏 24
24 条回复







C/C++ 工具平台和程序库