Item 4. Extensible Templates: Via Inheritance or Traits?

I l @ ve RuBoard

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.

  1. What is a traits class?

  2. 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 a const member function named Clone() 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: It's obvious that if C writes code that just tries to invoke T::Clone() without parameters, then such code will fail to compile if there isn't a T::Clone() that can be called without parameters. But that's not enough to answer this question, because just trying to call T::Clone() without parameters would also succeed in calling a Clone() that has default parameters and/or does not return a T* . The goal here is to specifically enforce that T provide a function that looks exactly like this: T* T::Clone() const .

  3. A programmer wants to write a template that can require (or just detect) whether the type on which it is instantiated has a Clone() member function. The programmer decides to do this by requiring that classes offering such a Clone() must derive from a predetermined Cloneable base class. Demonstrate how to write the following template:

     template<typename T> class X {   // ... }; 
    1. to require that T be derived from Cloneable ; and

    2. to provide an alternative implementation if T is derived from Cloneable , and work in some default mode otherwise .

  4. Is the approach in #3 the best way to require/detect the availability of a Clone() ? Describe alternatives.

  5. How useful is it for a template to know that its parameter type T is derived from some other type? Does knowing about such derivation give any benefit that couldn't also be achieved without the inheritance relationship?

I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net