Skip to main content

Section 23.4 Operations in Templated Code

Although in theory a templated function can be used with any data type, instantiating the template only works if all of the operations used in the function are valid for the data type.
For example, if we write a templated function that uses the less-than operator (<), then any data type we want to apply that template to must support the less-than operator. If we try to use the function with a type that does not support <, we will get a compiler error. Consider the following sample that tries to use our myMax function on a Time struct:
Listing 23.4.1.
The key part of the error message looks like this:
test.cpp:6:15: error: no match for โ€˜operator>โ€™ (operand types are โ€˜Timeโ€™ and โ€˜Timeโ€™)
    6 |     return (a > b) ? a : b;
When the compiler tries to build a version of myMax for the Time struct, it looks for the > operator to compare two Time objects. Since we havenโ€™t defined this operator for Time, the compiler doesnโ€™t know how to compare them and generates an error.
To fix this, we need to define the > operator for the Time struct:
Listing 23.4.2.
This requirement is why operator overloading is an important part of C++ programming. By defining the > operator for the Time struct, we allow that struct to work in any templated code that requires >.
You have attempted of activities on this page.