简体   繁体   中英

Reading range from std::array

How can I accept a std::array which might have a different dimension? This should be known at compile-time but the following won't work

template<int n>
void read_interval(size_t start, size_t end, std::array<n, char>& dest)

I also know that end-start == n so that might be somehow templated either.

You have the template arguments for std::array the wrong way round and the non-type argument is a std::size_t , not an int :

template<std::size_t n>
void read_interval(size_t start, size_t end, std::array<char,n>& dest)
{
    //...
}

You can't statically ensure that end - start == n as start and end are runtime values. If you really need that static assurance, you'll need to make them template parameters, otherwise you can use a runtime assert for debug mode or carry out a check and throw an exception.

You need to template the size argument, just like you did. Except you've swapped the order of the template parameters of std::array which is why it doesn't work.

Such code compiles, you should use size_t instead of int as template parameter

#include <array>

template<size_t n>
void read_interval(size_t start, size_t end, std::array<char, n>& dest)
{
}

int main()
{
    std::array<char, 10> arr1;

    read_interval(0, 10, arr1);

    std::array<char, 8> arr2;

    read_interval(0, 8, arr2);
}

end if n is always equal end you can just use n inside read_interval as ordinary constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM