CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2014

Temp Spec Lab

Links to the various pages for this class:

Wish I could do this: * Schedule

Template Specialization Lab

In this lab, we will look at some examples of Template Specialization. The files are in ~cs253/pub/Labs/TempSpecLab.

A Bar Graph Template

In 1.cc, we have a program that defines the BarGraph template. Here’s how to use it:

        BarGraph<int> alpha;
        alpha += 12;
        alpha += 6;
        alpha += 4;
        alpha += 6;
        alpha.dump();

This create a BarGraph of integers, uses it to count four integers, and then produce this bar graph:

         4 *
         6 **
        12 *

This template has several features worth discussion:

Advantages of templates

The benefit of a template is its generality. BarGraph should work for any type, as long as it is (think “Duck Typing”):

  • assignable
  • comparable via <
  • printable via <<

including int, float, string, etc.

Disadvantages of templates

Sure, BarGraph works for lots of types, but it’s not the most efficient solution for all types. It uses a map, which is a general solution, but that generality is not always needed.

Consider 2.cc, which introduces template specialization. It features a hand-written version BarGraph<bool>. This is a version of BarGraph tuned specially for counting booleans. Of course, the general version of BarGraph still exists, so it works for all other types, too.

The specialization BarGraph<bool> is:

(Of course, it’s certainly possible that g++’s implemention of map has a specialization for map<bool,whatever> that is smaller & faster in just that way. Who knows?)

Exercises

  1. Instead of .dump(), overload << so that you can insert a BarGraph object into an ostream.
  2. Create a specialization for BarGraph<char> that uses more efficient storage than a map. How can you portably determine the range of possible values for a char? (Try the numeric_limits class, provided by <limits>.)

For extra fame & glory:

  1. Add an operator so that you can do graph += "foo" for a BarGraph<char>. This should be equivalent to:
        graph += 'f';
        graph += 'o';
        graph += 'o';

Modified: 2009-04-27T13:28

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building