Reputation: 6950
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.
Upvotes: 0
Views: 117
Reputation: 9394
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.
Upvotes: 0
Reputation: 238341
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.
Upvotes: 0
Reputation: 65620
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.
Upvotes: 1