2012-11-27 30 views
3

一個簡單的C++文件和類TT有兩種方法。一個C++類函數

#include <map> 
#include <string> 
#include <iostream> 

using namespace std; 

class TT{ 
    public: 
     TT(const string& str); 
     template<class T>T Read(const string& key)const; 
     template<class T>T Read(const string& key, const T& value)const; 
}; 

TT::TT(const string& str){ 
    cout<<str<<endl; 
} 

template<class T>T TT::Read(const string& key)const{ 
    std::cout<<key<<std::endl; 
    return 1; 
} 

template<class T>T TT::Read(const string& key, const T& value)const{ 
    std::cout<<key<<'\t'<<value<<std::endl; 
    return value; 
} 

int main(void){ 
    TT tt("First"); 

    tt.Read("Hello", 12); 
    return 1; 
} 

如果

tt.Read("Hello world!", 12); 

tt.Read("Hello world!"); 

替換主()

G ++表示:

new.cc:31: error: no matching function for call to ‘TT::Read(const char [5])’

爲什麼G ++無法找到讀(const字符串&鍵)const方法?

謝謝!

+0

它只是工作在G ++ 4.7.2 – billz

+0

@billz,失敗對我來說:http://ideone.com/ymUPB5 –

回答

6

你試圖定義一個返回t的函數:

template<class T> 
T TT::Read(const string& key) const 
{ 
    std::cout << key << std::endl; 
    return 1; 
} 

但是,你總是從這個函數返回一個int。您需要像這樣稱呼它:

tt.Read<int>("Hello"); 

或者刪除模板定義,因爲它在這裏沒有意義。

+0

你剛纔說我的答案,但有更多的單詞。+1 – 2012-11-27 03:24:11

+0

帶參數的版本讓編譯器自動導出模板參數'T';沒有參數你必須明確給模板類型。 –

+0

THX,幫助我! – foool

1

您的函數template<class T>T Read(const string& key)const;以T類型爲模板,但T僅顯示爲返回類型。

如果你打算手動烤返回類型到您的函數(現在看來似乎是從return 1;外觀),你可以聲明更改爲類似:

int Read(const string& key) const; 

否則你必須在呼叫作爲人工手動指定模板類型:

tt.Read<int>("Hello"); 

這歸結爲一個事實,即當模板類型的回報僅僅出現一個函數不能有一個模板類型推斷。

C++標準說,這在某種程度上對部分眼中題爲容易得多:

Explicit template argument specification [temp.arg.explicit]

If all of the template arguments can be deduced, they may all be omitted; in this case, the empty template argument list <> itself may also be omitted. In contexts where deduction is done and fails, or in contexts where deduction is not done, if a template argument list is specified and it, along with any default template arguments, identifies a single function template specialization, then the template-id is an lvalue for the function template specialization.

template<class X, class Y> X f(Y); 

int i = f<int>(5.6); // Y is deduced to be double 
int j = f(5.6); // ill-formed: X cannot be deduced 
1

我相信這是因爲與模板打交道時,編譯器想知道返回函數是什麼,即使它返回1(這是一個int),它也不能算出來。技術上return 1可能是一個錯誤,因爲它不知道返回值應該是什麼。

使用tt.Read<int>("Hello");