by matthavener · 13y ago · 0 comments
void foo(int (&foo)[10]) {}
However, that is not "minimum of 10" but "exactly 10".You can also get the size at compile time:
template <size_t N> void foo(int (&foo)[N]) { int newarry[N+2]; }
I've used the above for something like this: template <size_t N> void safe_strcpy(char (&buf)[N], const char *src) {
strncpy(buf, src, N-1);
buf[N-1] = 0;
} template <size_t N>
typename enable_if<(N >= 10), void>::type
foo(int (&bar)[N]) { ... }
EDIT: Changed condition from N >= 0 into a more meaningful one. X-) template <size_t N>
foo(int (&bar)[N])
{
static_assert(N >= 10, "Array needs >= 10 elements!");
...
} template <size_t N>
typename enable_if<(1 < N && N < 10), void>::type
foo(int (&bar)[N])
{
// called when 1 < N && N < 10
}
template <size_t N>
typename enable_if<(N >= 10), void>::type
foo(int (&bar)[N])
{
// called when N >= 10
}
OTOH, the key advantage in static_assert is the meaningful error message.There'a an interesting analogy with structs here. K&R invented the -> operator specifically to obviate (* ptr).member. It's too bad that arrays took a different route through C's history and didn't manage to end up in a place where a similar convenience would make sense.