gpt4 book ai didi

c++ - c++ 中带有容器迭代器的循环类型依赖(GCC 失败,而 MSVC 正常)

转载 作者:太空狗 更新时间:2023-10-29 20:36:46 24 4
gpt4 key购买 nike

我写的原始代码在微软的编译器中开箱即用,但不能用 gcc (4.7.4) 编译:这是简化的代码:

// test.cpp
#include <unordered_map>
using namespace std;

struct order_rec;
typedef unordered_map<int, order_rec> placed_orders_t;
typedef placed_orders_t::iterator placed_order_iterator;
typedef unordered_map<int, placed_order_iterator> book_list_t;
typedef book_list_t::iterator book_list_iterator;
struct order_rec
{
int a;
book_list_iterator bi;
};

int main()
{
book_list_t test1;
order_rec test2;
}

g++ 不喜欢这一行:typedef placed_orders_t::iterator placed_order_iterator;,它会出错,因为那行 struct order_rec 没有完全声明。

如您所见,我有一个映射 placed_orders_t of int => order_rec,然后我有另一个映射 book_list_t 将 int 映射到迭代器到 placed_orders_t map 。然后,order_rec 本身将一个 interator 存储到 book_list_t 映射中。

请注意,我认为这是 gcc 的 unordered_map 实现(或者可能是编译器本身)中的一个错误:如果我将 placed_orders_t 键入为 std::map,那么一切都可以正常编译;但是,我确实需要在那里使用无序映射。

什么可以用作解决方法?

这是 g++ 编译的相关部分

g++-4.7 -O3 -DNDEBUG -std=c++11 -c test.cpp
...
/usr/include/c++/4.7/bits/unordered_map.h:264:11: required from ‘class std::unordered_map<int, order_rec>’
test.cpp:7:24: required from here
/usr/include/c++/4.7/bits/stl_pair.h:94:11: error: ‘std::pair<_T1, _T2>::second’ has incomplete type
test.cpp:5:8: error: forward declaration of ‘struct order_rec’

最佳答案

您的代码是未定义的行为。当你写:

struct order_rec;
typedef unordered_map<int, order_rec> placed_orders_t;
typedef placed_orders_t::iterator placed_order_iterator;

这需要实例化 placed_orders_t ,这需要实例化 unordered_map<int, order_rec> . order_rec在这一点上是不完整的。来自 [res.on.functions]:

In particular, the effects are undefined in the following cases: [...] if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

标准库中的某些类模板允许不完整的类型(如 unique_ptrvector ),但 unordered_map不是其中之一,所以它的影响是不确定的。编译失败是允许的结果。请注意,map 也是如此。 ,即使您的代码可以编译。

您必须拥有 placed_orders_t::mapped_type是可以在此上下文中使用的类型。也许std::unique_ptr<order_rec>

关于c++ - c++ 中带有容器迭代器的循环类型依赖(GCC 失败,而 MSVC 正常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37327531/

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