CS253: Software Development with C++

Spring 2021

Template

a Template Lab

made at imgflip.com

In this lab, we will look at some examples of Template Specialization. The files are in ~cs253/Lab/Template. Create a file called results.cc, and turn it in for credit.                 

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 += 6;
    alpha.dump();

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

     4 *
     6 ***
    12 *

This template class 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”): 🦆

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. It’s like how a chainsaw can cut through just about anything, but it’s not really practical for eating dinner. Sometimes, a more specialized tool is appropriate.                 

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 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                

How to submit your work:                

In Canvas, check in the file results.cc to the assignment “Lab11”. It’s due 10:00:00ᴘᴍ MT Saturday, with a 24-hour late period for a 25% penalty.                 

How to receive negative points:                

Turn in someone else’s work.