【发布时间】:2017-09-13 02:04:46
【问题描述】:
考虑以下示例 (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 设为非模板会使示例编译。
尽管从 int 隐式转换为 S<T>,为什么这段代码无法编译?
【问题讨论】:
-
T不能在S<T>中推导出来。这可能看起来很奇怪,但考虑到只存在从int到S<float>的转换的情况,T应该是什么? -
或者
S<int>没有那个构造函数 -
请注意
f<int>(1, 2)compiles fine。
标签: c++ templates compiler-errors