代码之家  ›  专栏  ›  技术社区  ›  gauss256

为什么此模板在Xcode中有错误,而不是在Visual Studio中?

  •  4
  • gauss256  · 技术社区  · 16 年前

    在C++中使用模板时,XCODER中出现了一个错误。有人能告诉我怎么了吗?

    第一个版本在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);
    }
    

    第二个没有错误。不同之处在于模板参数的使用 纵长 在模板化typedef中。

    // 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);
    }
    
    2 回复  |  直到 16 年前
        1
  •  5
  •   wilhelmtell    16 年前

    错误的原因是编译器不知道什么 graph_traits<Graph>::vertex_descriptor 是 . 它是静态成员还是类型?如果它是一种类型,那么你必须这样说:

    typename graph_traits<Graph>::vertex_descriptor
    

    LengthT 是模板参数。它可以 任何东西 ,因此,在模板声明时,编译器无法判断其值将是什么,因此typedef不明确。

        2
  •  5
  •   Georg Fritzsche    16 年前

    vertex_descriptor 是依赖类型(取决于模板参数 LengthT )因此你必须使用 typename :

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

    在第二个示例中,将删除对模板参数的依赖关系(而是使用固定类型- 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在这方面不符合要求,并且 “伟大” 用于开发不可移植的模板代码。