Search code examples
c++templatesstdarray

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.


Solution

  • 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.