Chapter 4. Extensible Templates: Via Inheritance or Traits?
Difficulty: 7
This Item reviews traits templates and demonstrates some cool traits techniques. Even without traits, what can a template figure out about its type—and what can it do about it? The answers are nifty and illuminating, and not just for people who write C++ libraries.
What is a traits class?
Demonstrate how to detect and make use of template parameters' members, using the following motivating case: You want to write a class template
C
that can be instantiated only on types that have aconst
member function namedClone()
that takes no parameters and returns a pointer to the same kind of object.// T must provide T* T::Clone() const template<typename T> class C { // ... };
Note: ...
Get More Exceptional C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.