C++ Primer(第 5 版)第 16.3 节 - 重载和模板 - 教授在存在候选函数模板实例化的情况下的函数匹配过程。
以下是本节中使用的函数模板的声明:
using std::string;
template <class T> string debug_rep(const T &); /* 1 */
template <class T> string debug_rep(T *); /* 2 */
// definitions not relevant for the questions
第一个例子
string s("SO");
debug_rep(&s);
据说生成的实例将是:
-
debug_rep(const string *&)
(with T
势必string *
)
debug_rep(string *)
Q1#1 正确吗?它不应该实例化吗debug_rep(string* const &)
反而?
第二个例子
const string *sp = &s;
debug_rep(sp); //string literal type is const char[10]
据说生成的实例将是:
-
debug_rep(const string *&)
(with T
势必const string *
)
debug_rep(const string *)
因此,两个实例化的候选者将提供精确的匹配,在更专业的模板上进行选择(->#2)
Q2.1#1 正确吗?它不应该实例化吗debug_rep(const string* const &)
?
Q2.2假设实例化的函数是上面的函数,我们是否可以断言它不再是完全匹配的?
第三个例子
debug_rep("SO world!"); //string literal type is const char[10]
据说生成的实例将是:
-
debug_rep(const T &)
(with T
势必char[10]
)
debug_rep(const string *)
因此,两个实例化的候选者将提供精确的匹配,在更专业的模板上进行选择(->#2)
Q3.1推导出的类型是T
#1 正确吗?不应该是吗const char[10]
反而 ?
Q3.2假设推导出的类型为T
实际上就是上面那个,我们可以断言它不再是完全匹配的吗?