Reputation: 5665
I have a container that stores another container. And I need to create an iterator for this container over nested container's values. This iterator should define an operator*
but I do not know the nested container's value type to return. I can not guarantee that container has any typedef
of the value. The only thing given is that each container has a proper operator[]
. How to declare the 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. I have only C++11 features available.
Upvotes: 3
Views: 191
Reputation: 14390
You can use decltype
:
auto operator*() -> decltype(Container[IndexA][IndexB])
{
return Container[IndexA][IndexB];
}
For this to work you should move the data members from the bottom of the class to the top. See this answer for the reason why.
An alternative is to place this->
before each data member access (decltype(this->Container[this->IndexA][this->IndexB])
).
Upvotes: 3
Reputation: 42899
If your compiler supports C++14 one solution would be to use decltype(auto)
in the following way:
decltype(auto) operator* () {
return (Container[IndexA][IndexB]);
}
Upvotes: 2