Rather than specializing the whole template, we can specialize just specific member function(s). For example, if Foo
is a template class with a member Bar
, we can specialize just that member:
template <typename T> struct Foo {
Foo(const T &t = T()): mem(t) { }
void Bar() { /* ... */ }
T mem;
// other members of Foo
};
template<> // we're specializing a template
void Foo<int>::Bar() // we're specializing the Bar member of Foo<int>
{
// do whatever specialized processing that applies to ints
}
Here we are specializing just one member of the Foo<int>
class. The other members of Foo<int>
will be supplied by the Foo
template:
Foo<string> fs; // instantiates Foo<string>::Foo()
fs.Bar(); // instantiates Foo<string>::Bar()
Foo<int> fi; // instantiates Foo<int>::Foo()
fi.Bar(); // uses our specialization of Foo<int>::Bar()
When we use Foo
with any type other than int
, members are instantiated as usual. When we use Foo
with int
, members other than Bar
are instantiated as usual. If we use the Bar
member of Foo<int>
, then we get our specialized definition.
Exercise 16.62: Define your own version of hash<Sales_data>
and define an unordered_multiset
of Sales_data
objects. Put several transactions into the container and print its contents.
Exercise 16.63: Define a function template to count the number of occurrences of a given value in a vector
. Test your program by passing it a vector
of double
s, a vector
of int
s, and a vector
of string
s.
Exercise 16.64: Write a specialized version of the template from the previous exercise to handle vector<const char*
> and a program that uses this specialization.
Exercise 16.65: In § 16.3 (p. 698) we defined overloaded two versions of debug_rep
one had a const char*
and the other a char*
parameter. Rewrite these functions as specializations.
Exercise 16.66: What are the advantages and disadvantages of overloading these debug_rep
functions as compared to defining specializations?
Exercise 16.67: Would defining these specializations affect function matching for debug_rep
? If so, how? If not, why not?