2
考虑下面的例子(godbolt):编译它提供了以下错误调用带有自变量的函数隐式转换为模板类的一个对象
template <typename T>
struct S {
S(int) {}
};
template <typename T>
void f(S<T>, T) {}
int main() {
f(1, 2);
}
:
<source>: In function 'int main()':
10 : <source>:10:11: error: no matching function for call to 'f(int, int)'
f(1, 2);
^
7 : <source>:7:6: note: candidate: template<class T> void f(S<T>, T)
void f(S<T>, T) {}
^
7 : <source>:7:6: note: template argument deduction/substitution failed:
10 : <source>:10:11: note: mismatched types 'S<T>' and 'int'
f(1, 2);
^
制作S
非-template使示例编译。
尽管隐式从int
转换为S<T>
,但为何不编译此代码?
'T'不能在'S'中推导出来。这可能看起来很奇怪,但考虑只有从“int”到“S ”的转换存在的情况,“T”应该是什么? –
或者'S'没有那个构造函数 –
请注意'f(1,2)'[compiles fine](https://ideone.com/DoOa3F)。 –
dasblinkenlight