16.62 Sales_data类要包含==运算符,主程序代码如下:
#include "Sales_data.h"
#include <unordered_set>
using namespace std;
namespace std {
template <>
struct hash<Sales_data>
{
typedef size_t result_type;
typedef Sales_data argument_type;
size_t operator()(const Sales_data& s) const;
};
size_t
hash<Sales_data>::operator()(const Sales_data &s) const
{
return hash<string>()(s.bookNo) ^
hash<unsigned>()(s.units_sold) ^
hash<double>()(s.revenue);
}
}
int main()
{
unordered_multiset<Sales_data> SDset;
Sales_data item;
while (read(cin, item)) {
SDset.insert(item);
}
cout << SDset.size() << endl;
for (auto sd : SDset)
{
print(cout, sd) << endl;
}
return 0;
}
16.63
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
template <typename T>
size_t count(vector<T> &v, const T &t)
{
size_t ret = 0;
for (auto ev : v) {
if (t == ev)
++ret;
}
return ret;
}
template <>
size_t count(vector<const char*> &v, const char* const &p)
{
size_t ret = 0;
for (auto ev : v) {
if (!strcmp(ev, p))
++ret;
}
return ret;
}
int main()
{
vector<double> vd = { 1.1, 3.14, 2.2, 3.14, 3.3, 4.4};
cout << count(vd, 3.14) << endl;
vector<int> vi = { 0, 1, 2, 3, 4, 5 };
cout << count(vi, 0) << endl;
vector<string> vs = { "Hello", "World", "!" };
cout << count(vs, string("end")) << endl;
string s1("cat");
string s2("dog");
string s3("rat");
const char *p1 = s1.c_str();
const char *p2 = s2.c_str();
const char *p3 = s3.c_str();
const char *p4 = s2.c_str();
vector<const char *> vp;
vp.push_back(p1);
vp.push_back(p2);
vp.push_back(p3);
vp.push_back(p4);
cout << count(vp, p2) << endl;
return 0;
}
16.64 已包含在上题代码中
16.65
template <>
string debug_rep(char *p)
{
return debug_rep(string(p));
}
template <>
string debug_rep(const char *cp)
{
return debug_rep(string(cp));
}
16.66 当不能或不希望使用通用模板版本时,可以定义类或函数的特例化版本;对重载而言,在函数匹配过程中会在重载函数中选择最佳匹配,需要小心设计,避免实际匹配不符合预期。
16.67 特例化版本不会影响函数匹配,只是接管实例化工作,当某个模板是最佳匹配,且将其实例化为该特殊实例时,不再从原模板实例化,而直接使用特例化版本。