看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) dev c++ 小弟在研讀template時,對於function template 重載產生了些許疑問 因此寫了個測試程式,程式為以下的部分 template<class T> void test(const T&,const T&) { cout<<"Template"<<endl; } void test(const char*,const char*) { cout<<"Non-template"<<endl; } int main() { char x[]="Apple"; char y[]="abcd"; char* x1=x; char* x2=y; test(x,y); test(x1,x2); system("pause"); return 0; } output: Non-template Template =============================== 在此第一次呼叫test function時, 會有兩個候選函式 1.是將template的type訂為 char*的template function 2.一般的test function 而因為編譯器必須將array name轉換成pointer,因此按照呼叫的順序就會呼叫一般函式 而第二次呼叫test function時, 依然會有兩個候選函式 1.是將template的type訂為 char*的template function 2.一般的test function 這次因為傳入的是pointer to char,而在template function中 可以直接使用不用轉型 但是在一般函式中必須將char* 轉成 const char* 故會呼叫template function 所以依照這樣的結果,我是不是可以做出下列的結論 1.array name 雖然可以直接當作一pointer指向第一個元素的位置,但是需要接受轉換的 步驟 2.當函式的參數是reference to const type時,我們可以傳遞nonconst變數給它,而此 變數不需要經過轉換就可以使用 (函式的參數如為reference to const,我們可以餵nonconst的變數給它) 3.當函式的參數是pointer to const type時,如果我們傳遞pointer to nonconst type 時,此pointer就需要先轉換成const pointer 但是我又作了實驗我將一般函式改成下式然後將 function tempalte刪除 void test(const char*&,const char*&) { cout<<"Non-template"<<endl; } 但是如此一來兩個test function的呼叫都會產生錯誤 是因為在char*要轉型成 const char*&時 char*->const char*->const char* & 其中 const char*這個位置會是一個tempory的值 因此無法讓reference 綁定 所以造成錯誤嗎? 那這樣不就跟結論的第二點產生矛盾 如果有說明不清的地方,請多多指正 謝謝各位 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.115.0.73