0

I'm trying to get the multi_index_t code from the second answer here answered by davidhigh to work with C++11. C++11 does not support auto& type returns.

I converted the return types for the class, but I don't understand how/if it's possible to support the helper function multi_index() without using C++14.

The code:

#include<array>

template<int dim>
struct multi_index_t
{
  std::array<int, dim> size_array;
  template<typename ... Args>
  multi_index_t(Args&& ... args) : size_array(std::forward<Args>(args) ...) {}

  struct iterator
  {
    struct sentinel_t {};
    std::array<int, dim> index_array = {};
    std::array<int, dim> const& size_array;
    bool _end = false;

    iterator(std::array<int, dim> const& size_array) : size_array(size_array) {}

    iterator& operator++() 
    {
      for (int i = 0;i < dim;++i)
      {
        if (index_array[i] < size_array[i] - 1)
        {
          ++index_array[i];
          for (int j = 0;j < i;++j) { index_array[j] = 0; }
          return *this;
        }
      }
      _end = true;
      return *this;
    }
    std::array<int, dim>& operator*()  { return index_array; }
    bool operator!=(sentinel_t) const { return !_end; }
  };

  iterator begin() const { return iterator{ size_array }; }
  iterator end() const { return typename iterator::sentinel_t{}; }
};


template<typename ... index_t>
auto multi_index(index_t&& ... index) // <-- this doesn't compile
{
  static constexpr int size = sizeof ... (index_t); 
  auto ar = std::array<int, size>{std::forward<index_t>(index) ...};
  return multi_index_t<size>(ar);
}

According to this answer, you can't recursively expand the variadic function template via decltype(). Any ideas?

max66
  • 65,235
  • 10
  • 71
  • 111
Peek
  • 23
  • 1
  • 4

1 Answers1

0

C++11 does not support auto& type returns.

So you can simply explicit the types.

For multi_index() you have that return a multi_index_t<size>, where size is sizeof...(index_t), so you can write

template<typename ... index_t>
multi_index_t<sizeof...(index_t)> multi_index(index_t&& ... index)

According to this answer, you can't recursively expand the variadic function template via decltype.

Correct, but I don't see recursion in your multi_index() function, so I don't see how apply recursion over decltype().

If you really want (but why?), you can explicit the returning type through decltype() as follows

template<typename ... index_t>
auto multi_index(index_t&& ... index)
   -> decltype( multi_index_t<sizeof...(index_t)>
                   { std::array<int, sizeof...(index_t)>
                        {{ std::forward<index_t>(index) ... }} } )

but I don't see a reason to do this instead of simply explicit multi_index_t<sizeof...(index_t)>

max66
  • 65,235
  • 10
  • 71
  • 111