Reputation: 16741
What are the cons of the inheriting from the traits class template in my own (say, conatiner) template class? Is it conventional, legal?
Upvotes: 1
Views: 1789
Reputation: 76376
Only traits can inherit other traits (in the strict sense of what C++ standard library calls *_traits
), if they should only differ in some aspects. But there are other similar classes intended for inheriting that simplify defining the members. E.g. when defining iterator, you are probably going to inherit std::iterator
to define the appropriate tag typedefs.
Upvotes: 4
Reputation: 154047
It depends, sort of. I would distinguish between the OO concept
of inheritance, and the C++ implementation technique of
derivation. (This choice of vocabulary is personal. The
distinction is not often made, but IMHO, it is important to
distinguish between the design concept, and the implementation
technique.) In this case, I would say that you don't inherit
from a traits class, since there is no isA relationship. On the
other hand, while derivation is usually used to implement
inheritance, it's not the only possible use. It's perfectly
normal to derive from a traits class (e.g. in the way most
iterators will derive from std::iterator
), as long as it is
clear that this derivation is not used to implement
inheritance, in the OO sense. In particular, you don't want
people manipulating your iterator through pointers to
std::iterator
.
It has been suggested (by none less than Herb Sutter) that
traits classes have protected destructors, to prevent any risk
of deletion through them. I'm not totally convinced. The very
semantics of a traits class are such that it won't normally even
occur to anyone to create a pointer to one. (When was the last
time you saw an std::iterator*
in any code?) (On the other
hand, one may ask: why not? The protected destructor does mean
that the traits class is not a POD, but I can't think of any
reasonable case where this matters.)
Any way, publicly inheriting from a traits class to obtain
a number of typedef
is a standard C++ idiom.
Upvotes: 1
Reputation: 24626
Normally, traits classes are just a bunch of typedefs. If you want to have them all in your class, you can inherit from them. Since they usually have no (nonstatic) members, they are in fact empty classes, so inheriting from them means that the Empty Base Class Optimization applies. So what the cons could be:
More material on inheritance, EBCO etc.:
Upvotes: 3