The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #27
Programming with C++
Class templates, template specialization
Warm up: iterator invalidation
What's wrong with the following program?
auto find( std::vector<int> v, int x )
{
auto end = v.end();
auto iter = v.begin();
for ( ; iter != end; ++iter )
if ( *iter == x )
break;
return iter;
}
int main() {
std::vector<int> v = { 11, 22, 33, 44, 55, 66, 77, 99 };
assert( find( v, 42 ) == v.end() );
}
Class templates
- Class template defines a blueprint for a family of classes.
- To use a specific class instance of a class template, we must supply class template arguments in the angle brackets following the class template name:
std::vector<int>
- In contrast to function templates, except for a couple of specific contexts, we have to explicitly provide the class template parameters; the compiler will not deduce them for us.
- The act of generating a specific instance of a class template by the compiler is called template instantiation.
- A member function of a class template is instantiated only if the program uses that member function.
Template specialization
How can we change class and/or function template implementation for specific (sets of) template arguments?
Problem:
When instantiated with bool, our class point takes 2 bytes. Can we make it more space efficient?
Example 1:
template< typename T > struct point {
point() : x(), y() {}
point( T x, T y ) : x( x ), y( y ) {}
T x;
T y;
};
int main() {
point<bool> p;
assert( sizeof( p ) == 1 ); // possible?
}
Template specialization (cont.)
Function zero_fill sets the value of all elements of vector to 0. Can we make it more efficient for, say, vector<int>?
Example 2:
template< typename T >
void zero_fill( vector<T>& v )
{
for ( auto& x : v )
x = 0;
}
Programming with C++, Fall 2019, Lecture #27
By Aleksey Gurtovoy
Programming with C++, Fall 2019, Lecture #27
Class templates, template specialization
- 592