The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #27
Class templates, template specialization
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() );
}
std::vector<int>
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?
}
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;
}