这是由 this 激发的文章(第5页)
template<class T>
T const &f(T const &a, T const &b){
return (a > b ? a : b);
}
template int const &f<int>(int const &, int const &);
int main(){
int x = 0, y = 0;
short s = 0;
f(x, y); // OK
f(x, s); // Is this call well-formed?
}
是调用'f(x, s)'
良构?我假设因为函数模板 'f'
被显式实例化,将应用标准转换,因此 'short s'
将转换为 'int'
匹配对显式特化的调用 'f<int>'
.但这似乎是错误的?
标准的哪一部分讨论了这种情况下的适用规则?
最佳答案
不,调用 f(x, s)
格式不正确。由于您没有明确说明要使用的特化,因此编译器使用参数推导来尝试实例化函数模板;这失败了,因为 x
和 s
有不同的类型,所以 T
是不明确的。
适用的规则在13.3.1的重载解析过程的规范中:
In each case where a candidate is a function template, candidate function template specializations are generated using template argument deduction (14.8.3, 14.8.2). Those candidates are then handled as candidate functions in the usual way.
14.8.3/1 也是相关的:
For each function template, if the argument deduction and checking succeeds, the template arguments (deduced and/or explicit) are used to instantiate a single function template specialization which is added to the candidate functions set to be used in overload resolution. If, for a given function template, argument deduction fails, no such function is added to the set of candidate functions for that template.
函数模板被显式实例化为T = int
,但编译器不知道它应该使用这个实例化,直到它执行模板参数推导以确定什么T
应该是。
关于c++ - 显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723630/