CS 70

Key Points

Templates

  • A template is a recipe for generating code that works with different types.

    • A template has template parameters that can be filled in with various types.
    • Declare a template with, for example, template <typename T> (where T is the parameter)
    • You can have function templates and class templates.
  • A template cannot be compiled on its own.

    • The actual instructions would differ for different types.
    • So a template must be compiled along with code that uses it (provides specific template arguments).
  • Typical file structure for templates.

    • A source file that uses the template includes
      • my-templated-thing.hpp, which
        • Contains traditional “header-file” content (declarations, etc.)
        • And—at the bottom of the file—#includes
          • my-templated-thing-private.hpp, which
            • Contains traditional “source-file” content (definitions, etc.)
      • There is no my-templated-thing.cpp file.

Type Conversion

  • When choosing which function to call for overloading, for each argument an exact match on the type is best, then a template-based argument, then type conversion.
  • Type conversion between classes is possible, but only if one of the classes specifies how. There are two ways to do it:
    • The “target” class can define conversion by creating a single-parameter constructor and/or creating a specialized version of the assignment operator.
    • The “source” class can define conversion by creating a type-casting operator.
  • If you don't want a single-parameter constructor or type-casting operator to be used for implicit conversion, you should use the explicit keyword.
  • There are limits to how much conversion the compiler will do:
    • It will only perform conversion once; it won't do a “chain” of conversions.
    • It will only perform conversion for parameters to a function; you can't apply conversion to a value that you're calling a member function on.

(When logged in, completion status appears here.)