练习16.48
编写你自己版本的debug_rep函数。
解答:
这个可以参考书中的实现。可能需要实现多个,来让编译器进行匹配。
练习16.49
解释下面每个调用会发生什么:
template <typename T> void f(T);
template <typename T> void f(const T*);
template <typename T> void g(T);
template <typename T> void g(T*);
int i = 42, *p = &i;
const int ci = 0, *p2 = &ci;
g(42);
g(p);
g(ci);
g(p2);
f(42);
f(p);
f(ci);
f(p2);
解答:
“->”代表匹配
g(42) -> g(T)
g(p) -> g(T*)
g(ci)->g(T)
g(p2) -> g(T*)
f(42) -> f(T)
f(p) -> f(T)
f(ci) -> f(T)
f(p2) -> f(const T*)
这里的特例化,说实在的,还真的有些难理解。
练习16.50
定义上一个练习中的函数,令他们打印一条身份信息。运行该练习中的代码。如果函数调用的行为于你的预期不符,确定你理解了原因
解答:
#include <utility>
#include <string>
#include <iostream>
using namespace std;
template <typename T> void f(T a){
cout << " void f(T a)" << endl;
}
template <typename T> void f(const T* a){
cout << " void f(const T a)" << endl;
}
template <typename T> void g(T a){
cout << " void g(T a)" << endl;
}
template <typename T> void g(T* a){
cout << " void g(T* a)" << endl;
}
int main(){
int i = 42, *p = &i;
const int ci = 0, *p2 = &ci;
g(42);
g(p);
g(ci);
g(p2);
f(42);
f(p);
f(ci);
f(p2);
}