2010-09-21 39 views
1

我想我碰到了一個(可能的)VC6(我知道了,這是我們使用的,)編譯器錯誤,但我開放的事實是我錯過了一些愚蠢的事實。考慮下面的代碼(這只是一個例子!):由模板成員函數引起的錯誤C2275。這段代碼錯了嗎?

#include <iostream> 

// Class with template member function: 
class SomeClass 
{ 
public: 
    SomeClass() {}; 

    template<class T> 
    T getItem() 
    { 
    return T(); 
    }; 
}; 


// Dummy just used to recreate compiler error 
class OtherClass 
{ 
public: 
    OtherClass() {}; 
}; 

std::ostream& operator<<(std::ostream& oStr, const OtherClass& obj) 
{ 
    return oStr << "OtherClass!"; 
}; 

// Main illustrates the error: 
int main(int argc, char* argv[]) 
{ 
    SomeClass a; 

    OtherClass inst2 = a.getItem<OtherClass>(); // Error C2275 happens here! 
    std::cout << inst2 << std::endl; 

    return 0; 
} 

如果我嘗試編譯這段代碼VC6,模具上a.getItem<OtherClass>()產生:

Error C2275: 'OtherClass' : illegal use of this type as an expression

我忽略了一些微不足道的語法問題嗎?我打破規則? 這段代碼在gcc 4.3.4下編譯得很好。這是VC6的另一個合規性問題嗎?

謝謝!

回答

1

這很可能是一個VC6問題。儘管VC6能夠正確編譯大多數基本模板,但當您開始轉向更高級的模板使用時,已知存在許多問題。成員模板是VC6已知在一致性方面較弱的領域。

+0

I'除非有人出現,否則就會把這個作爲正確的答案! – acanaday 2010-09-21 21:23:14

1

我相信這是VC6中的另一個錯誤,您應該切換到更新的編譯器。

+0

_I_會**愛**到。不幸的是,我不能。 – acanaday 2010-09-21 20:54:03

+0

http://www.cplusplus.com/forum/general/11928/試試這個。 – 2010-09-21 20:56:22

+0

然後你需要使用非模板解決方案:( – Goz 2010-09-21 20:57:03

2

在其中有template這個詞的許多其他事物中,VC6無法處理模板參數不是函數參數的函數模板。常見的解決方法是添加一個虛擬函數參數:

template<class T> 
    T getItem(T* /*dummy*/ = NULL) 
    { 
    return T(); 
    } // note: no ; after function definitions 

然而,在一般情況下,VC6是相當失敗,往往只要一個TU包含template關鍵字扼流圈。我不得不在幾年內反對它(大編碼基礎編譯了幾個編譯器/編譯器版本; VC6給了我們無窮的麻煩),並且當我在2003年擺脫它時感到非常高興。