2010-07-29 50 views
4

在C++中使用模板時,出現Xcode錯誤。有人能告訴我什麼是錯的嗎?爲什麼這個模板在Xcode中有錯誤,但不是Visual Studio?

第一個版本在Xcode中報告錯誤,但在Visual Studio中報告錯誤。

// Version 1: Error in Xcode, but not Visual Studio 
template<typename LengthT, typename VertexT> 
int MyGraphAlgorithm(...arguments omitted...) 
{ 
    using namespace boost; 

    typedef property<vertex_distance_t, LengthT> VertextProperties_t; 
    typedef adjacency_list<vecS, vecS, directedS, VertextProperties_t> Graph; 
    // In next line Xcode reports: "error: expected `;' before 'vertexInitial'" 
    graph_traits<Graph>::vertex_descriptor vertexInitial(100); 
} 

第二個沒有錯誤。區別在於在模板化類型定義中使用模板參數LengthT

// Version 2: No error in Xcode or Visual Studio 
template<typename LengthT, typename VertexT> 
int MyGraphAlgorithm(...arguments omitted...) 
{ 
    using namespace boost; 

    // In the following line, LengthT has been changed to int 
    typedef property<vertex_distance_t, int> VertextProperties_t; 
    typedef adjacency_list<vecS, vecS, directedS, VertextProperties_t> Graph; 
    graph_traits<Graph>::vertex_descriptor vertexInitial(100); 
} 

回答

5

錯誤的原因是編譯器不知道什麼graph_traits<Graph>::vertex_descriptor。它是一個靜態成員還是一個類型?如果它是一個類型,那麼你必須這麼說:

typename graph_traits<Graph>::vertex_descriptor 

原因編譯器是沒有足夠的智慧弄清楚自身是因爲LengthT是一個模板參數。它可以是任何東西,所以在模板聲明時編譯器不能告訴它的值是什麼,並且typedef因此是不明確的。

+0

修復它,謝謝。 – gauss256 2010-07-30 05:43:10

5

vertex_descriptor是一個依賴型(這取決於模板參數LengthT),從而必須使用typename

typename graph_traits<Graph>::vertex_descriptor vertexInitial(100); 

在上模板參數的depency除去第二個例子(你使用固定類型 - int),因此沒有錯誤。

一個更加簡單的重現這樣:

template<class T> struct A { typedef T type; }; 
template<class T> struct B { 
    A<T>::type t1; // wrong, works with VS but not with conforming compilers 
    typename A<T>::type t2; // correct 
}; 

Visual Studio是知道在這方面是不符合要求的,是發展不可移植的模板代碼「偉大」

+0

我懷疑這是一個非標準的VS「擴展」。謝謝(你的)信息。 – gauss256 2010-07-30 05:42:41

相關問題