11.7.  Review Questions

[ fromfile: generics-questions.xml id: generics-questions ]

  1. Explain an important difference between a template parameter and a function parameter.

      A function parameter must be a constant or a variable, while a template parameter can also be (and most commonly is) a type expression such as int, QObject, Person*.

  2. What does it mean to instantiate a template function? Describe one way to do this.

      Calling a template function with actual arguments is one way to instantiate a template function. In general, using a template definition, by providing actual template parameters, is how you can get the compiler to generate the template code for the specific type you are using.

  3. Normally, you need to place template definitions in header files. Why is this?

      Because, like any inline functions, because the compiler must substitute the definition in the code where the invocation is encountered, the definition must be known by the compiler. The linker will not resolve it later. The exception to this is with compilers which support export and maintain a database of template instantiations which get built along with the object modules. Such compilers blur the distinction between a compiler and a linker, but c'est la vie.

  4. Some compilers support export. What is it for?

      Export makes it possible for template definitions in one source module to be used in others, linked in a linker-like fashion. It helps reduce the code-size of a program, and also eliminates redundant code.

  5. Qt's container classes are used to collect value types. What kinds of things are not appropriate to store by value in a value collection?

      QObjects, polymorphic collections in general, and any class that can not be copied because it has no copy constructor.

  6. Which containers provide a mapping from key to value? List and describe at least two, and tell how they are different from one another.

      QMap and QHash.

  7. What does it mean for a container to "manage" its heap objects? How can a container of pointers to heap objects become a "managed container"?

  8. Give at least three examples of Qt classes that implement the Flyweight pattern.

      QList, QString, QSet.

  9. When defining a class template, how should the code be distributed between the header (.h) file and the implementation (.cpp) file? Explain your answer.

     Template definitions (classes and functions) must all be located in the header file. This is necessary for the compiler to generate code from a template declaration. Also the template declaration code template<class T> must precede each class or function definition that has a template parameter in its name.