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

这一生的挚爱 提交于 2021-02-16 14:03:58

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/26535139/creating-an-stdarray-with-size-calculated-during-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!