VS C++ compiler的一個bug

來源:互聯網
上載者:User
我在VS2010裡面寫入了如下代碼:
#include <iostream>#include <typeinfo>using namespace std;template<typename T>void function(const T& value){    cout<<typeid(value).name()<<endl;}class CT{public:    friend void function(int iValue);};int main(){    function(0);}

    然後我編譯的時候提示我連結錯,其意思就是找不到function的定義。但是,根據C++標準,此處應該調用的是template<T>function()。
1,class裡面的friend function如果沒有在外面聲明的話,在外圍是不可見的,也就是說CT裡面的那個friend function在外圍是不可見的,自然地,在main裡面的那個function調用是不可能綁定在CT裡面的friend
function。 2,有個外圍的template<T> function,這個是完全可以通過參數演繹使main裡面的那個function調用成功得到解釋。    另外,我把代碼改成如下所示,在VS2010裡面的輸出結果更讓人奇怪

#include <iostream>#include <typeinfo>using namespace std;template<typename T>void function(const T& value){    cout<<typeid(value).name()<<endl;}class CT{public:    friend void function(int iValue){         cout<<"friend int CT called!"<<endl;    }};int main(){    function(0);}
   按照VS的理論,應該調用CT裡面的那個friend function,也就是應該輸出friend in CT called!,然而,事實上輸出的是int,這表明VS也是調用的是template<T>
function,這裡就有一個問題了,既然VS也是調用template<T> function,那麼,它又為什麼給出一個Link error提示呢?    再次把代碼改成如下所示:
#include <iostream>#include <typeinfo>using namespace std;template<typename T>void function(const T& value){    cout<<typeid(value).name()<<endl;}void function(int iValue);//使CT 裡面的friend function對外可見class CT{public:    friend void function(int iValue){        cout<<"friend int CT called!"<<endl;    }};int main(){    function(0);}

    此時就會輸出friend in CT called,這證明了在(1)中的理論是成立的。
   綜上所述,這是VS2010 C++ compiler裡面的一個bug。(MAC OS 的XCode 4.3.2裡面這代碼是可以成功地編譯。)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.