2016-05-13 16 views
3

我有一個容器來存儲另一個容器。我需要通過嵌套容器的值爲這個容器創建一個迭代器。這個迭代器應該定義一個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; 
}; 

P.S.我只有C++ 11功能可用。

回答

3

您可以使用decltype

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

對於這個工作,你應該將數據成員類的底部到頂部移動。 See this answer for the reason why

另一種方法是在每個數據成員訪問(decltype(this->Container[this->IndexA][this->IndexB]))之前放置this->

+0

也許我應該指出,這是我試過的第一件事。結果是'錯誤C2065:'容器':未聲明的標識符' – teivaz

+0

@teivaz嘗試將'this->'放在'Container'和'IndexA'和'IndexB'前面。 – Simple

+0

@teivaz http://ideone.com/5h9I9u – Simple

2

如果你的編譯器支持C++ 14一個解決辦法是通過以下方式使用decltype(auto)

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

Live Demo

+0

我知道這個解決方案,但我只有C++ 11的支持。 – teivaz