error: no matching function for call to '...'(テンプレートの型推論失敗)の原因と直し方
テンプレート関数の2つの引数に異なる型を渡したときに出るエラーです。同じ型パラメータTを2箇所で使うテンプレートは、呼び出し時にすべての箇所で矛盾なく同じ型が推論できなければコンパイルできません。
エラーメッセージの読み方
main.cpp:7:21: error: no matching function for call to 'add(int, const char [2])'
main.cpp- ファイル名
7- 行番号
21- 列番号 — この位置でg++が構文解析に失敗しました
no matching function for call to 'add(int, const char [2])'- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 #include <iostream> 2 template <typename T> 3 T add(T a, T b) { 4 return a + b; 5 } 6 int main() { 7 std::cout << add(3, "5") << std::endl; ^ 8 return 0; 9 }
main.cpp:7:21: error: no matching function for call to 'add(int, const char [2])'
同じ型パラメータTを2箇所で使うテンプレートは、両方の引数から矛盾なく同じ型が推論できないとコンパイルできません。3はint、"5"はconst char*で型が異なるため推論に失敗します。
直し方: "5" を 5 にします。
広告
広告スロット(未設定)
パターン2
1 #include <iostream> 2 template <typename T> 3 T maxOf(T a, T b) { 4 return a > b ? a : b; 5 } 6 int main() { 7 std::cout << maxOf(10, 3.5) << std::endl; ^ 8 return 0; 9 }
main.cpp:7:23: error: no matching function for call to 'maxOf(int, double)'
テンプレートは呼び出しごとに具体的な型を1つに確定できて初めてコンパイルが通ります。10はint、3.5はdoubleで型が異なるため、コンパイラはTを1つに決められません。
直し方: 3.5 を 3 にします。
パターン3
1 #include <iostream> 2 template <typename T> 3 T multiply(T a, T b) { 4 return a * b; 5 } 6 int main() { 7 std::cout << multiply(4, '2') << std::endl; ^ 8 return 0; 9 }
main.cpp:7:26: error: no matching function for call to 'multiply(int, char)'
「テンプレートは何でも受け付けてくれる万能な関数」というのは誤解です。'2'はchar型であり、4のint型とは別の型として扱われるため型推論が失敗します。
直し方: '2' を 2 にします。
よくある誤解
「テンプレートは何でも受け付けてくれる万能な関数」というのは誤解です。テンプレートは呼び出しごとに具体的な型を1つに確定できて初めてコンパイルが通ります。引数ごとに異なる型を渡すと、コンパイラはTを1つに決められず型推論に失敗します。
まとめ
error: no matching function for call to '...'(テンプレートの型推論失敗)の原因と直し方は上級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。