2013-08-18 30 views
2

爲什麼我會收到編譯錯誤no matching function for call to `f(__gnu_cxx::__normal_iterator > >)'爲什麼C++不能找到模板函數?

#include <vector> 

template<typename T> 
void f(const typename std::vector<T>::iterator &) {} 

void g() { 
    std::vector<int> v; 
    f<int>(v.end()); // Compiles. 
    f(v.end()); // Doesn't compile, gcc 4.3 can't find any match. 
} 

最後,我想編寫一個函數,只需要一個矢量迭代器和編譯失敗(有一個有意義的錯誤)的任何東西。所以template<typename T>void f(const T&) {}不是一個好的解決方案,因爲它也編譯爲其他類型。

+0

這有什麼錯你有?編譯錯誤的原因是您沒有爲模板化函數調用提供類型。即使你提供了'int'作爲向量類型,你仍然需要爲'f'調用指定它。 – Chris

+2

[C++,模板參數不能被推斷]的可能的重複(http://stackoverflow.com/questions/6060824/c-template-argument-can-not-be-deduced) – Mehrdad

回答

3

G ++ 4.8給出了更完整的消息:http://ideone.com/ekN3xs

note: template argument deduction/substitution failed: 
note: couldn't deduce template parameter ‘T’ 

f不直接需要T(如在 「const T& 」)或類型,其中T清楚(如在「 const std::vector<T>&」),但嵌套相關類型(這裏爲std::vector<T>::iterator),所以模板類型T不能從參數中自動推導出來。

編輯:Dietmar Kühl's answer給出了一個很好的理由例子。


爲了您的「最終」的一部分,檢查How to check whether a type is std::vector::iterator at compile time?(公認的答案使用一些C++ 11點的類型,但是你可以使用C++ 03等價物,例如從升壓)

+0

另請參見視頻http:// channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-2-of-n#time=37m30s(從大約37:30到42 :00) –

4

不能從嵌套類型中推導出模板參數。想想,例如,std::vector<T>::size_type總是std::size_t:編譯器如何解決歧義?我意識到在你的例子中情況並非如此,但同樣的原則適用。例如,迭代器類型std::vector<T>可以是T*,它也可以是迭代器類型std::array<T, N>

相關問題