Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deduce nested container value type

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.

like image 805
Teivaz Avatar asked May 10 '26 13:05

Teivaz


2 Answers

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])).

like image 63
Simple Avatar answered May 13 '26 03:05

Simple


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]);
}

Live Demo

like image 22
101010 Avatar answered May 13 '26 02:05

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!