6

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?

T.C.
  • 133,968
  • 17
  • 288
  • 421
max
  • 2,627
  • 1
  • 24
  • 44
  • 6
    `std::array`'s size must be known at compile time. The run-time-sized array is `std::vector`. – T.C. Oct 23 '14 at 18:59
  • 1
    As T.C. says, the answer to your question is "You can't create a `std::array` with size calculated at run time." You can either use `std::vector`, or give us some more information about the problem you are trying to solve so we can suggest alternative approaches. – Casey Oct 23 '14 at 19:03
  • 4
    it would be nice to state the reason for the down vote. There's no problem with my question the problem is the C++ language capabilities. – max Oct 23 '14 at 19:18
  • The actual question is why there is no way to make a constant-length `vector`. It is a good question, but one that cannot be answered in SO. – Elazar Oct 23 '14 at 19:27
  • 4
    @Elazar I didn't know it's impossible. If i knew I wouldn't ask it in the first place. – max Oct 23 '14 at 19:32

1 Answers1

4

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;
Elazar
  • 20,415
  • 4
  • 46
  • 67
  • I didn't get your point could you please elaborate it with an example? – max Oct 23 '14 at 19:34
  • It is not imprtant. Whatever you need it to be. – Elazar Oct 23 '14 at 19:54
  • the compiler complains about the value of `n` not being initialized with a constant expression. I mean i can't call this function with `maxLength(some_array.size())`. – max Oct 23 '14 at 20:10
  • 1
    your answer did not solve my problem but I learned a new technique which is using recursion in `constexpr` functions. – max Oct 24 '14 at 03:01