Search code examples
c++c++11constexprstdarray

creating an std::array with size calculated during run time


I want to create an object of std::array<T, N> but the problem is I can only use functions that return a constexprtype or compiler will complain. The problem here is that I need to calculate the length of this array based on another array's size which could be something like this:

template <typename T>
struct DataLength 
{
    template <typename iter>
    size_t maxPossibleLength(iter begin, iter end) 
    {
        size_t m_size = 0;
        while (begin != end) {
            m_size = m_size << 8 | std::numeric_limits<T>::max(); /* 0xff for uchar*/
            begin++;
        }
        return m_size;
    }
}

how can i convert the output of this function so i can use it instead of N?


Solution

  • You can write this as a recursive constexpr function, and do the calculation on the length of the original array, which should be compile time too.

    The thing is that your function (if i understood it correctly) need not get an iterator at all. It needs a length N. so it can do something like:

    template<typename T>
    constexpr size_t maxLength(size_t n, size_t m_size=0) {
        return n==0 ? m_size : maxLength<T>(n-1, m_size << 8 | std::numeric_limits<T>::max());
    }
    

    And it runs:

    std::array<int, 15> a;
    std::array<float, maxLength<int>(a.size())> b;