如何推导嵌套的容器值类型

How to deduce nested container value type

本文关键字:类型 何推导 嵌套      更新时间:2023-10-16

我有一个存储另一个容器的容器。我需要在嵌套容器的值上为这个容器创建一个迭代器。这个迭代器应该定义一个operator*,但我不知道要返回的嵌套容器的值类型。我不能保证容器有任何值为的typedef。唯一给出的是每个容器都有一个合适的operator[]。如何申报operator*

template<typename ContainerType>
struct MyIterator{
MyIterator(ContainerType& container, int32 indexA = 0, int32 indexB = 0)
    : Container(container)
    , IndexA(indexA)
    , IndexB(indexB)
{}
// NestedValueType needs to be replaced or declared somehow
NestedValueType& operator* ()
{
    return Container[IndexA][IndexB];
}
private:
    ContainerType& Container;
    int32 IndexA;
    int32 IndexB;
};

附言:我只有C++11功能可用。

您可以使用decltype:

auto operator*() -> decltype(Container[IndexA][IndexB])
{
    return Container[IndexA][IndexB];
}

要做到这一点,您应该将数据成员从类的底部移动到顶部。请参阅此答案以了解原因。

一种替代方案是在每个数据成员访问(decltype(this->Container[this->IndexA][this->IndexB]))之前放置this->

如果您的编译器支持C++14,一个解决方案是以以下方式使用decltype(auto)

decltype(auto) operator* () {
  return (Container[IndexA][IndexB]);
}

实时演示