2010-07-29 49 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

相关问题