【问题标题】:How to deduce nested container value type如何推断嵌套容器值类型
【发布时间】:2016-05-13 09:19:26
【问题描述】:

我有一个存储另一个容器的容器。我需要在嵌套容器的值上为这个容器创建一个迭代器。这个迭代器应该定义一个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 功能可用。

【问题讨论】:

    标签: c++ templates c++11 containers


    【解决方案1】:

    你可以使用decltype:

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

    为此,您应该将数据成员从类的底部移动到顶部。 See this answer for the reason why.

    另一种方法是在每个数据成员访问之前放置this-&gt; (decltype(this-&gt;Container[this-&gt;IndexA][this-&gt;IndexB]))。

    【讨论】:

    • 也许我应该提到这是我尝试过的第一件事。结果是error C2065: 'Container' : undeclared identifier
    • @teivaz 尝试将this-&gt; 放在ContainerIndexAIndexB 前面。
    • 您也可以将数据成员移动到类的顶部而不是底部,并删除this-&gt;
    • 随着 cmets 的更改,它可以工作。只需将它们编辑为答案,我会解决它。
    【解决方案2】:

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

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

    Live Demo

    【讨论】:

    • 我知道那个解决方案,但我只支持 C++11。
    猜你喜欢
    • 2022-12-07
    • 2011-05-11
    • 2018-07-26
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多