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