gpt4 book ai didi

c++ - 为什么这个模板在 Xcode 中有错误,而在 Visual Studio 中没有?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:34 26 4
gpt4 key购买 nike

在 C++ 中使用模板时,我在 Xcode 中遇到错误。谁能告诉我哪里出了问题?

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

最佳答案

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

typename graph_traits<Graph>::vertex_descriptor

编译器不够聪明,无法自行解决的原因是 LengthT是模板参数。它可以是任何东西,因此在模板声明时编译器无法判断它的值是什么,因此 typedef 是不明确的。

关于c++ - 为什么这个模板在 Xcode 中有错误,而在 Visual Studio 中没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3367761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com