【发布时间】:2013-03-04 18:14:43
【问题描述】:
在“C++ 模板 - 完整指南”一书的 2.4 Overloading Function Templates 部分中,您将找到以下示例:
// maximum of two int values
inline int const& max (int const& a, int const& b)
{
return a < b ? b : a;
}
// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a < b ? b : a;
}
// maximum of three values of any type
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
return max (max(a,b), c);
}
int main()
{
::max(7, 42); // calls the nontemplate for two ints (1)
}
然而,在附录 B 的 B.2 简化重载解决方案中,作者指出:
注意重载解析发生在模板参数推导之后,...(2)
根据(2),::max(7,42)应该通过参数推导调用max<int>。
【问题讨论】:
-
当在模板参数推导后完成重载决议时,为什么它应该更喜欢另一个呢?在这一点上它们本质上是相同的,但是我认为编译器会选择最适合的那个,并且 AFAIK 更喜欢非模板而不是模板。
-
为什么(2)暗示
max<int>?您已经推导出了模板参数,但您仍然需要解决重载问题,包括非模板函数。
标签: c++ templates template-argument-deduction