Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎

Lesson 9

This week's tasks are:

  • C++ template practices

Practice 1

Comparing two values (such as numerical, string and some other data type values) is a routine task you would see in many programs. Your first task is to code the following functions as template functions:

  • bool less(const T &val1, const T &val2) // returns true if (val1<val2) is true.

  • bool greater(const T &val1, const T &val2) // returns true if (val1>val2) is true.

  • bool equal(const T &val1, const T &val2) // returns true if (val1==val2) is true.

  • T average(const T &val1, const T &val2) // returns an average of val1 and val2

define them so that they can only be visible (usable) within that source, which contains the statements using those functions.

Practice 2

Once you finish coding the above code, test your template function with various data types. You should test it at least with the following data types:

  • int
  • float
  • char
  • string

Practice 3

Your next task is to build a generic template class, which implements comparison of two values. Your template class should appropriately overload:

  • bool operator<

  • bool operator<=

  • bool operator>

  • bool operator>=

  • bool operator==
  • bool operator!=

as well as providing a getter method to retrieve the value (getValue()).

Practice 4

Once the above template class is programmed, check its behaviour with various data types. You should test it at least with the following data types:

  • int
  • float
  • char
  • string

Practice 5

Modify your code so that your comparison template class compare two strings based on their "length" rather than the order in a dictionary.

Practice 6

Write your template class code in a header file (XXX.h). Furthermore, provide function body outside of the class definition. Once you separate the class definition and the function definition, put some function definitions in a separate file (XXX.cpp).

Write your main() function, which tests your template class, in a separate file (YYY.cpp), and compile the project.

You should try various combinations of where to put the function definitions in order to use the template without linker errors.

Practice 7

Write a main() function, which tests your template class with two or more cases of the same data type. For instance:

...
    Comp<int> values[] = {32, 44, 559, 321, 98};
    Comp<int> values2[] = {859, 484, 399, 21, 2398};
...

And confirm that only one generated Comp class to deal with int type exists.


Sample Solutions


Subpages (1): Sample Solutions
Comments