【发布时间】:2015-06-16 11:24:59
【问题描述】:
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 *&)(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 *&)(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 &)(T绑定到char[10]) debug_rep(const string *)
因此,两个实例化的候选者都将提供完全匹配,在更专业的模板上进行选择 (-> #2)
Q3.1 #1 中为T 推断的类型是否正确?不应该是const char[10]吗?
Q3.2 假设T 的推导类型实际上就是上面那个,我们可以确定它不再是完全匹配了吗?
【问题讨论】:
-
能否请对问题投反对票的用户详细说明其原因,以便我可以尝试将我的问题提高到标准?
-
是的,我认为作者在这一章上有点落伍了。我在 16.2.5 结束时发现了另一个错误 - 与非模板函数一样,第一个版本将绑定到可修改的右值,第二个版本将绑定到左值或 const 右值。 不正确,请尝试传递
f的非 const 左值表达式,第一个被调用,而不是第二个(由于引用折叠)。
标签: c++ templates type-deduction