2011-12-30 47 views
1

這是我的代碼:爲什麼沒有尖括號的非限定模板函數的實例不能成爲類的朋友?

#include<iostream> 

class foo; 
template<typename T> void bar(T a) { std::cout<< a.var; } 

class foo { 
    int var; 
    public: 
     friend void bar(foo); //here, bar function template is declared in global namescope, 
     // deduction can deduce which template instance we're talking about. 
     //Note: If I place <> just after name bar or qualify bar like ::bar , it all works then. 
}; 

int main() { 
    foo fooo; 
    bar(fooo); 
} 

錯誤:/home/O1wLF2/cc1xOI20.o:在函數 '主':prog.cpp :(文本+ 0×46):未定義參照「巴(富) '

我想知道爲什麼非合格模板函數的實例不能成爲朋友?

回答

3

您正在使一個非模板功能成爲朋友。你需要告訴編譯器你想將一個模板變成一個朋友或一個實例。

+0

我不同意你的看法,試着運行相同的程序,包括僅僅在''bar''這樣的'bar'條件下,甚至沒有使用MSVS中的<>(http://www.ideone.com/cZ6jA),它就會運行精細。 – 2011-12-30 21:00:38

+1

類中的friend聲明聲明瞭一個名爲bar()的非模板函數,並將foo對象作爲參數。這與上面聲明(和定義)的函數模板沒有任何關係。那麼,這是函數模板的重載,當參數類型完全匹配時,它是首選。如果你明確限定bar(),它不能是一個聲明,顯然,找到函數模板。不過,兩件事情不同。 – 2011-12-30 21:28:06

+1

@Anubis先生:我不知道代碼應該證明或反駁的是什麼,但[this](http://ideone.com/C4B9L)是您需要查看的代碼。 – ildjarn 2011-12-30 21:32:29

相關問題