【发布时间】:2014-03-10 12:51:14
【问题描述】:
在his answer 到this question 和评论部分,Johannes Schaub 表示在尝试对需要的参数多于已传递参数的函数模板进行模板类型推导时出现“匹配错误”:
template<class T>
void foo(T, int);
foo(42); // the template specialization foo<int>(int, int) is not viable
在另一个问题的上下文中,相关的是函数模板的类型推导是否成功(并且发生替换):
template<class T>
struct has_no_nested_type {};
// I think you need some specialization for which the following class template
// `non_immediate_context` can be instantiated, otherwise the program is
// ill-formed, NDR
template<>
struct has_no_nested_type<double>
{ using type = double; };
// make the error appear NOT in the immediate context
template<class T>
struct non_immediate_context
{
using type = typename has_no_nested_type<T>::type;
};
template<class T>
typename non_immediate_context<T>::type
foo(T, int) { return {}; }
template<class T>
bool foo(T) { return {}; }
int main()
{
foo(42); // well-formed? clang++3.5 and g++4.8.2 accept it
foo<int>(42); // well-formed? clang++3.5 accepts it, but not g++4.8.2
}
在为T == int 实例化第一个函数模板foo 时,替换会产生一个不在foo 直接上下文中的无效类型。这会导致一个硬错误(这就是the related question 的意义所在。)
然而,当让foo 推导出它的模板参数时,g++ 和 clang++ 同意没有实例化发生。如Johannes Schaub explains,这是因为存在“匹配错误”。
问题:什么是“匹配错误”,标准中在何处以及如何指定?
替代问题:为什么 foo(42) 和 foo<int>(42) 对于 g++ 有区别?
到目前为止我发现/尝试了什么:
[over.match.funcs]/7 和 [temp.over] 似乎描述了函数模板的重载解析细节。后者似乎要求用模板参数替换foo。
有趣的是,[over.match.funcs]/7 触发了 [temp.over] before 中描述的过程,检查函数模板的可行性(特化)。 类似地,类型推导不考虑默认函数参数(除了使它们成为非推导上下文)。据我所知,它似乎并不关心可行性。
另一个可能重要的方面是如何指定类型推导。它作用于单个函数参数,但我看不出包含/依赖于模板参数的参数类型(如T const&)和不依赖于模板参数的参数类型(如int)之间的区别。
然而,g++ 在显式指定模板参数(硬错误)和让它们被推断(推断失败/SFINAE)之间有所不同。为什么?
【问题讨论】:
标签: c++ templates overload-resolution template-argument-deduction