2013-08-21 111 views
0

我有這樣的代碼:沒有匹配函數調用

class XMLNode 
    { 
     //... 
     template <typename T> 
     bool getValue(T& t, const std::string& path) const 
     { 
      if (empty()) 
      { 
       throw std::runtime_error("Empty node"); 
      } 
      return nsXML::getValue(t, path, *node); 
     } 

     template <typename T> 
     T getValue(const std::string& path) const 
     { 
      if (empty()) 
      { 
       throw std::runtime_error("Empty node"); 
      } 
      return nsXML::getValue<T>(path, *node); 
     } 
     //... 
    }; 

class XMLData 
{ 
    //... 
    template <typename T> 
    T getValue(const std::string& path) 
    { 
     return XMLNode(&mDocNode, 0).getValue(path); // ERROR LINE 
    } 
    //... 
}; 

,給我錯誤

no matching function for call to ‘nsXML::XMLNode::getValue(const string&)’ 
note: candidates are: 
note: template<class T> bool nsXML::XMLNode::getValue(T&, const string&) const 
note: template<class T> T nsXML::XMLNode::getValue(const string&) const 

爲什麼g++給我這個錯誤?

+2

你需要傳遞一些模板參數該成員函數調用:'的XMLNode(mDocNode, 0).getValue (path);' – juanchopanza

回答

1

編譯器無法評估您想要實例化函數模板的類型。在這種情況下,你必須明確地指定它:

return XMLNode(&mDocNode, 0).getValue<T>(path); 
            // ^-- explicit instantiation 

只有在某些情況下,模板參數可以通過編譯器自動從函數參數推斷:

int i; 
bool b = XMLNode(&mDocNode, 0).getValue(i, path); 

這裏,編譯器看到一個int作爲第一個函數參數,並可以推斷T代表該函數調用爲int,所以它的同

bool b = XMLNode(&mDocNode, 0).getValue<int>(i, path); 
0

因爲你的XMLNode :: getValue(const std :: string & path)函數是一個const,所以當它調用nsXML :: getValue時,它正在尋找const版本,我想沒有定義一個const 。

注意一個const成員函數和一個非const成員函數是不同的。